var DefaultDateFormat = 'DD-MM-YYYY';
var HideWait = 3; // Кол-во секунд перед закрытием календаря
var Y2kPivotPoint = 30;
var UnselectedMonthText = 'Выбор';
var FontSize = 11;
var FontFamily = 'Tahoma';
var CellWidth = 18;
var CellHeight = 16;
var ImageURL = '../../images/lib/calendar.jpg';
var NextURL = '../../images/lib/next.gif';
var PrevURL = '../../images/lib/prev.gif';
var CalBGColor = 'white';
var TopRowBGColor = 'buttonface';
var DayBGColor = 'lightgrey';
// Глобальные переменные
var ZCounter = 100;
var Today = new Date();
var WeekDays = new Array('Вс','Пн','Вт','Ср','Чт','Пт','Сб');
var MonthDays = new Array(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
var MonthNames = new Array('Январь','Февраль','Март','Апрель','Май','Июнь','Июль','Август','Сентябрь','Октябрь','Ноябрь','Декабрь');
with (document)
{
writeln('');
}
// В области ввода года только цифры
function YearDigitsOnly(e)
{
var KeyCode = (e.keyCode) ? e.keyCode : e.which;
return ((KeyCode == 8) || (KeyCode == 9) || (KeyCode == 37) || (KeyCode == 39) || (KeyCode == 46) || ((KeyCode > 47) && (KeyCode < 58)));
}
// Вычисляем абсолютное положение
function GetTagPixels(StartTag, Direction)
{
var PixelAmt = (Direction == 'LEFT') ? StartTag.offsetLeft : StartTag.offsetTop;
while ((StartTag.tagName != 'BODY') && (StartTag.tagName != 'HTML'))
{
StartTag = StartTag.offsetParent;
PixelAmt += (Direction == 'LEFT') ? StartTag.offsetLeft : StartTag.offsetTop;
}
return PixelAmt;
}
// Список выбора
function BehindCal(SelectList, CalLeftX, CalRightX, CalTopY, CalBottomY, ListTopY)
{
var ListLeftX = GetTagPixels(SelectList, 'LEFT');
var ListRightX = ListLeftX + SelectList.offsetWidth;
var ListBottomY = ListTopY + SelectList.offsetHeight;
return (((ListTopY < CalBottomY) && (ListBottomY > CalTopY)) && ((ListLeftX < CalRightX) && (ListRightX > CalLeftX)));
}
// Список выбора, только для IE
function FixSelectLists(Over)
{
if (navigator.appName == 'Microsoft Internet Explorer')
{
var CalDiv = this.getCalendar();
var CalLeftX = CalDiv.offsetLeft;
var CalRightX = CalLeftX + CalDiv.offsetWidth;
var CalTopY = CalDiv.offsetTop;
var CalBottomY = CalTopY + (CellHeight * 9);
var FoundCalInput = false;
formLoop :
for (var j = this.formNumber; j < document.forms.length; j++)
{
for (var i = 0; i < document.forms[j].elements.length; i++)
{
if (typeof document.forms[j].elements[i].type == 'string')
{
if ((document.forms[j].elements[i].type == 'hidden') && (document.forms[j].elements[i].name == this.hiddenFieldName))
{
FoundCalInput = true;
i += 3;
}
if (FoundCalInput)
{
if (document.forms[j].elements[i].type.substr(0,6) == 'select')
{
ListTopY = GetTagPixels(document.forms[j].elements[i], 'TOP');
if (ListTopY < CalBottomY)
{
if (BehindCal(document.forms[j].elements[i], CalLeftX, CalRightX, CalTopY, CalBottomY, ListTopY))
{
document.forms[j].elements[i].style.visibility = (Over) ? 'hidden' : 'visible';
}
}
else
{
break formLoop;
}
}
}
}
}
}
}
}
// Формируем сообщение в строке статуса
function DayCellHover(Cell, Over, Color, HoveredDay)
{
Cell.style.backgroundColor = (Over) ? DayBGColor : Color;
if (Over)
{
if ((this.yearValue == Today.getFullYear()) && (this.monthIndex == Today.getMonth()) && (HoveredDay == Today.getDate()))
{
self.status = 'Сегодняшняя дата';
}
else
{
var Suffix = HoveredDay.toString();
switch (Suffix.substr(Suffix.length - 1, 1))
{
case '1' : Suffix += (HoveredDay == 11) ? ' ' : ' '; break;
case '2' : Suffix += (HoveredDay == 12) ? ' ' : ' '; break;
case '3' : Suffix += (HoveredDay == 13) ? ' ' : ' '; break;
default : Suffix += ' '; break;
}
self.status = 'Выбор ' + this.monthName + ' ' + Suffix;
}
}
else
{
self.status = '';
}
return true;
}
// Устанавливаем элементы формы, после выбора
function PickDisplayDay(ClickedDay)
{
this.show();
var MonthList = this.getMonthList();
var DayList = this.getDayList();
var YearField = this.getYearField();
FixDayList(DayList, GetDayCount(this.displayed.yearValue, this.displayed.monthIndex));
// Месяц и день в списках
for (var i = 0; i < MonthList.length; i++)
{
if (MonthList.options[i].value == this.displayed.monthIndex)
MonthList.options[i].selected = true;
}
for (var j = 1; j <= DayList.length; j++)
{
if (j == ClickedDay)
DayList.options[j-1].selected = true;
}
this.setPicked(this.displayed.yearValue, this.displayed.monthIndex, ClickedDay);
// В случае необходимости меняем год
YearField.value = this.picked.yearPad;
YearField.defaultValue = YearField.value;
}
// Строим HTML
function BuildCalendarDays()
{
var Rows = 5;
if (((this.displayed.dayCount == 31) && (this.displayed.firstDay > 4)) || ((this.displayed.dayCount == 30) && (this.displayed.firstDay == 6)))
Rows = 6;
else if ((this.displayed.dayCount == 28) && (this.displayed.firstDay == 0))
Rows = 4;
var HTML = '
';
for (var j = 0; j < Rows; j++)
{
HTML += '';
for (var i = 1; i <= 7; i++)
{
Day = (j * 7) + (i - this.displayed.firstDay);
if ((Day >= 1) && (Day <= this.displayed.dayCount))
{
if ((this.displayed.yearValue == this.picked.yearValue) && (this.displayed.monthIndex == this.picked.monthIndex) && (Day == this.picked.day))
{
TextStyle = 'color : white; font-weight : bold;'
BackColor = DayBGColor;
}
else
{
TextStyle = 'color : black;'
BackColor = CalBGColor;
}
if ((this.displayed.yearValue == Today.getFullYear()) && (this.displayed.monthIndex == Today.getMonth()) && (Day == Today.getDate()))
TextStyle += 'border : 1px solid darkred; padding : 0px;';
HTML += '' + Day + ' | ';
}
else
HTML += ' | ';
}
HTML += '
';
}
return HTML += '
';
}
// Определяем какое столетие использовать
function GetGoodYear(YearDigits)
{
if (YearDigits.length == 4)
return YearDigits;
else
{
var Millennium = (YearDigits < Y2kPivotPoint) ? 2000 : 1900;
return Millennium + parseInt(YearDigits,10);
}
}
// Високосный год
function GetDayCount(SomeYear, SomeMonth)
{
return ((SomeMonth == 1) && ((SomeYear % 400 == 0) || ((SomeYear % 4 == 0) && (SomeYear % 100 != 0)))) ? 29 : MonthDays[SomeMonth];
}
// Кнопки
function VirtualButton(Cell, ButtonDown)
{
if (ButtonDown)
{
Cell.style.borderLeft = 'buttonshadow 1px solid';
Cell.style.borderTop = 'buttonshadow 1px solid';
Cell.style.borderBottom = 'buttonhighlight 1px solid';
Cell.style.borderRight = 'buttonhighlight 1px solid';
}
else
{
Cell.style.borderLeft = 'buttonhighlight 1px solid';
Cell.style.borderTop = 'buttonhighlight 1px solid';
Cell.style.borderBottom = 'buttonshadow 1px solid';
Cell.style.borderRight = 'buttonshadow 1px solid';
}
}
// Предыдущий/следующий месяц
function NeighborHover(Cell, Over, DateObj)
{
if (Over)
{
VirtualButton(Cell, false);
self.status = 'Просмотр ' + DateObj.fullName;
}
else
{
Cell.style.border = 'buttonface 1px solid';
self.status = '';
}
return true;
}
// Дни в зависимости от месяца и года
function FixDayList(DayList, NewDays)
{
var DayPick = DayList.selectedIndex + 1;
if (NewDays != DayList.length)
{
var OldSize = DayList.length;
for (var k = Math.min(NewDays,OldSize); k < Math.max(NewDays,OldSize); k++)
{
(k >= NewDays) ? DayList.options[NewDays] = null : DayList.options[k] = new Option(k+1, k+1);
}
DayPick = Math.min(DayPick, NewDays);
DayList.options[DayPick-1].selected = true;
}
return DayPick;
}
function FixYearInput(YearField)
{
var YearRE = new RegExp('\\d{' + YearField.defaultValue.length + '}');
if (!YearRE.test(YearField.value)) YearField.value = YearField.defaultValue;
}
// Сообщение
function CalIconHover(Over)
{
var Message = (this.isShowing()) ? '(закрытие)' : '(открытие)';
self.status = (Over) ? 'Просмотр ' + Message + ' календаря' : '';
return true;
}
// Starts the timer over from scratch
function CalTimerReset()
{
eval('clearTimeout(' + this.timerID + ')');
eval(this.timerID + '=setTimeout(\'' + this.objName + '.show()\',' + (HideWait * 1000) + ')');
}
// Таймер
function DoTimer(CancelTimer)
{
if (CancelTimer)
eval('clearTimeout(' + this.timerID + ')');
else
{
eval(this.timerID + '=null');
this.resetTimer();
}
}
// Показать/скрыть календарь
function ShowCalendar()
{
if (this.isShowing())
{
var StopTimer = true;
this.getCalendar().style.zIndex = --ZCounter;
this.getCalendar().style.visibility = 'hidden';
this.fixSelects(false);
}
else
{
var StopTimer = false;
this.fixSelects(true);
this.getCalendar().style.zIndex = ++ZCounter;
this.getCalendar().style.visibility = 'visible';
}
this.handleTimer(StopTimer);
self.status = '';
}
// Скрытие элементов
function SetElementStatus(Hide)
{
this.getDayList().style.visibility = (Hide) ? 'hidden' : 'visible';
this.getYearField().style.visibility = (Hide) ? 'hidden' : 'visible';
this.getCalendarLink().style.visibility = (Hide) ? 'hidden' : 'visible';
}
// Устанавливаем дату но основе выбранного месяца
function CheckMonthChange(MonthList)
{
var DayList = this.getDayList();
if (MonthList.options[MonthList.selectedIndex].value == '')
{
DayList.selectedIndex = 0;
this.hideElements(true);
this.setHidden('');
}
else
{
this.hideElements(false);
if (this.isShowing())
{
this.resetTimer();
this.getCalendar().style.zIndex = ++ZCounter;
}
var DayPick = FixDayList(DayList, GetDayCount(this.picked.yearValue, MonthList.options[MonthList.selectedIndex].value));
this.setPicked(this.picked.yearValue, MonthList.options[MonthList.selectedIndex].value, DayPick);
}
}
// Устанавливаем дату
function CheckDayChange(DayList)
{
if (this.isShowing()) this.show();
this.setPicked(this.picked.yearValue, this.picked.monthIndex, DayList.selectedIndex+1);
}
// Устанавливаем дату на основе выбранного года
function CheckYearInput(YearField)
{
if ((YearField.value.length == YearField.defaultValue.length) && (YearField.defaultValue != YearField.value))
{
if (this.isShowing())
{
this.resetTimer();
this.getCalendar().style.zIndex = ++ZCounter;
}
var NewYear = GetGoodYear(YearField.value);
var MonthList = this.getMonthList();
var NewDay = FixDayList(this.getDayList(), GetDayCount(NewYear, this.picked.monthIndex));
this.setPicked(NewYear, this.picked.monthIndex, NewDay);
YearField.defaultValue = YearField.value;
}
}
// Держим характеристики даты
function dateObject()
{
if (Function.call)
{
var ParentObject = this;
var ArgumentStart = 0;
}
else
{
var ParentObject = arguments[0];
var ArgumentStart = 1;
}
ParentObject.date = (arguments.length == (ArgumentStart+1)) ? new Date(arguments[ArgumentStart+0]) : new Date(arguments[ArgumentStart+0], arguments[ArgumentStart+1], arguments[ArgumentStart+2]);
ParentObject.yearValue = ParentObject.date.getFullYear();
ParentObject.monthIndex = ParentObject.date.getMonth();
ParentObject.monthName = MonthNames[ParentObject.monthIndex];
ParentObject.fullName = ParentObject.monthName + ' ' + ParentObject.yearValue;
ParentObject.day = ParentObject.date.getDate();
ParentObject.dayCount = GetDayCount(ParentObject.yearValue, ParentObject.monthIndex);
var FirstDate = new Date(ParentObject.yearValue, ParentObject.monthIndex, 1);
ParentObject.firstDay = FirstDate.getDay();
}
// Держим след даты в скрытом поле
function storedMonthObject(DateFormat, DateYear, DateMonth, DateDay)
{
(Function.call) ? dateObject.call(this, DateYear, DateMonth, DateDay) : dateObject(this, DateYear, DateMonth, DateDay);
this.yearPad = this.yearValue.toString();
this.monthPad = (this.monthIndex < 9) ? '0' + String(this.monthIndex + 1) : this.monthIndex + 1;
this.dayPad = (this.day < 10) ? '0' + this.day.toString() : this.day;
this.monthShort = this.monthName.substr(0,3).toUpperCase();
if (DateFormat.indexOf('YYYY') == -1) this.yearPad = this.yearPad.substr(2);
if (DateFormat.indexOf('/') >= 0) var Delimiter = '/';
else if (DateFormat.indexOf('-') >= 0) var Delimiter = '-';
else var Delimiter = '';
if (/DD?.?((MON)|(MM?M?))/.test(DateFormat))
{
this.formatted = this.dayPad + Delimiter;
this.formatted += (RegExp.$1.length == 3) ? this.monthShort : this.monthPad;
}
else if (/((MON)|(MM?M?))?.?DD?/.test(DateFormat))
{
this.formatted = (RegExp.$1.length == 3) ? this.monthShort : this.monthPad;
this.formatted += Delimiter + this.dayPad;
}
this.formatted = (DateFormat.substr(0,2) == 'YY') ? this.yearPad + Delimiter + this.formatted : this.formatted + Delimiter + this.yearPad;
}
// Object for the current displayed month
function displayMonthObject(ParentObject, DateYear, DateMonth, DateDay)
{
(Function.call) ? dateObject.call(this, DateYear, DateMonth, DateDay) : dateObject(this, DateYear, DateMonth, DateDay);
this.displayID = ParentObject.hiddenFieldName + '_Current_ID';
this.getDisplay = new Function('return document.getElementById(this.displayID)');
this.dayHover = DayCellHover;
this.goCurrent = new Function(ParentObject.objName + '.getCalendar().style.zIndex=++ZCounter;' + ParentObject.objName + '.setDisplayed(Today.getFullYear(),Today.getMonth());');
if (ParentObject.formNumber >= 0) this.getDisplay().innerHTML = this.fullName;
}
// Объект для кнопок вперед/назад
function neighborMonthObject(ParentObject, IDText, DateMS)
{
(Function.call) ? dateObject.call(this, DateMS) : dateObject(this, DateMS);
this.buttonID = ParentObject.hiddenFieldName + '_' + IDText + '_ID';
this.hover = new Function('C','O','NeighborHover(C,O,this)');
this.getButton = new Function('return document.getElementById(this.buttonID)');
this.go = new Function(ParentObject.objName + '.getCalendar().style.zIndex=++ZCounter;' + ParentObject.objName + '.setDisplayed(this.yearValue,this.monthIndex);');
if (ParentObject.formNumber >= 0) this.getButton().title = this.monthName;
}
function SetDisplayedMonth(DispYear, DispMonth)
{
this.displayed = new displayMonthObject(this, DispYear, DispMonth, 1);
this.previous = new neighborMonthObject(this, 'Previous', this.displayed.date.getTime() - 86400000);
this.next = new neighborMonthObject(this, 'Next', this.displayed.date.getTime() + (86400000 * (this.displayed.dayCount + 1)));
if (this.formNumber >= 0) this.getDayTable().innerHTML = this.buildCalendar();
}
// Устанавливаем обобранную дату
function SetPickedMonth(PickedYear, PickedMonth, PickedDay)
{
this.picked = new storedMonthObject(this.format, PickedYear, PickedMonth, PickedDay);
this.setHidden(this.picked.formatted);
this.setDisplayed(PickedYear, PickedMonth);
}
// Объект календаря
function calendarObject(DateName, DateFormat, DefaultDate)
{
this.hiddenFieldName = DateName;
this.monthListID = DateName + '_Month_ID';
this.dayListID = DateName + '_Day_ID';
this.yearFieldID = DateName + '_Year_ID';
this.monthDisplayID = DateName + '_Current_ID';
this.calendarID = DateName + '_ID';
this.dayTableID = DateName + '_DayTable_ID';
this.calendarLinkID = this.calendarID + '_Link';
this.timerID = this.calendarID + '_Timer';
this.objName = DateName + '_Object';
this.format = DateFormat;
this.formNumber = -1;
this.picked = null;
this.displayed = null;
this.previous = null;
this.next = null;
this.setPicked = SetPickedMonth;
this.setDisplayed = SetDisplayedMonth;
this.checkYear = CheckYearInput;
this.fixYear = FixYearInput;
this.changeMonth = CheckMonthChange;
this.changeDay = CheckDayChange;
this.resetTimer = CalTimerReset;
this.hideElements = SetElementStatus;
this.show = ShowCalendar;
this.handleTimer = DoTimer;
this.iconHover = CalIconHover;
this.buildCalendar = BuildCalendarDays;
this.pickDay = PickDisplayDay;
this.fixSelects = FixSelectLists;
this.setHidden = new Function('D','if (this.formNumber >= 0) this.getHiddenField().value=D');
this.getHiddenField = new Function('return document.forms[this.formNumber].elements[this.hiddenFieldName]');
this.getMonthList = new Function('return document.getElementById(this.monthListID)');
this.getDayList = new Function('return document.getElementById(this.dayListID)');
this.getYearField = new Function('return document.getElementById(this.yearFieldID)');
this.getCalendar = new Function('return document.getElementById(this.calendarID)');
this.getDayTable = new Function('return document.getElementById(this.dayTableID)');
this.getCalendarLink = new Function('return document.getElementById(this.calendarLinkID)');
this.getMonthDisplay = new Function('return document.getElementById(this.monthDisplayID)');
this.isShowing = new Function('return !(this.getCalendar().style.visibility != \'visible\')');
function getMonthIndex(MonthAbbr)
{
for (var MonPos = 0; MonPos < MonthNames.length; MonPos++)
{
if (MonthNames[MonPos].substr(0,3).toUpperCase() == MonthAbbr.toUpperCase()) break;
}
return MonPos;
}
function SetGoodDate(CalObj, Notify)
{
CalObj.setPicked(Today.getFullYear(), Today.getMonth(), Today.getDate());
//if (Notify) alert('WARNING: The supplied date is not in valid \'' + DateFormat + '\' format: ' + DefaultDate + '.\nTherefore, the current system date will be used instead: ' + CalObj.picked.formatted);
}
if (DefaultDate != '')
{
if ((this.format == 'YYYYMMDD') && (/^(\d{4})(\d{2})(\d{2})$/.test(DefaultDate)))
{
this.setPicked(RegExp.$1, parseInt(RegExp.$2,10)-1, RegExp.$3);
}
else
{
if ((this.format.substr(0,2) == 'YY') && (/^(\d{2,4})(-|\/)/.test(DefaultDate)))
{
var YearPart = GetGoodYear(RegExp.$1);
if (/(-|\/)(\w{1,3})(-|\/)(\w{1,3})$/.test(DefaultDate))
{
var MidPart = RegExp.$2;
var EndPart = RegExp.$4;
if (/D$/.test(this.format))
{
var DayPart = EndPart;
var MonthPart = MidPart;
}
else
{
var DayPart = MidPart;
var MonthPart = EndPart;
}
MonthPart = (/\d{1,2}/i.test(MonthPart)) ? parseInt(MonthPart,10)-1 : getMonthIndex(MonthPart);
this.setPicked(YearPart, MonthPart, DayPart);
}
else
{
SetGoodDate(this, true);
}
}
else if (/(-|\/)(\d{2,4})$/.test(DefaultDate))
{
var YearPart = GetGoodYear(RegExp.$2);
if (/^(\w{1,3})(-|\/)(\w{1,3})(-|\/)/.test(DefaultDate))
{
if (this.format.substr(0,1) == 'D')
{
var DayPart = RegExp.$1;
var MonthPart = RegExp.$3;
}
else
{
var MonthPart = RegExp.$1;
var DayPart = RegExp.$3;
}
MonthPart = (/\d{1,2}/i.test(MonthPart)) ? parseInt(MonthPart,10)-1 : getMonthIndex(MonthPart);
this.setPicked(YearPart, MonthPart, DayPart);
}
else
{
SetGoodDate(this, true);
}
}
else
{
SetGoodDate(this, true);
}
}
}
}
// Основная функция, которая создает элементы формы
function DateInput(DateName, Required, DateFormat, DefaultDate)
{
if (arguments.length == 0)
{
document.writeln('ОШИБКА: Неправильный вызов функции \'DateInput\': [имя из скрытого поля].');
}
else
{
if (arguments.length < 3)
{
DateFormat = DefaultDateFormat;
if (arguments.length < 2)
{
Required = false;
}
}
else if (/^(Y{2,4}(-|\/)?)?((MON)|(MM?M?)|(DD?))(-|\/)?((MON)|(MM?M?)|(DD?))((-|\/)Y{2,4})?$/i.test(DateFormat))
{
DateFormat = DateFormat.toUpperCase();
}
else
{
var AlertMessage = 'ВНИМАНИЕ: Формируемая дата \'' + DateName + '\' не корректна: ' + DateFormat + '\nБудет использоваться формат даты по умолчанию: ' + DefaultDateFormat;
DateFormat = DefaultDateFormat;
if (arguments.length == 4)
{
var CurrentDate = new storedMonthObject(DateFormat, Today.getFullYear(), Today.getMonth(), Today.getDate());
AlertMessage += '\n\nThe supplied date (' + DefaultDate + ') не интерпритируется с постовляемым форматом.\nБудет использована текущая дата системы: ' + CurrentDate.formatted;
DefaultDate = CurrentDate.formatted;
}
alert(AlertMessage);
}
if (!CurrentDate) var CurrentDate = new storedMonthObject(DateFormat, Today.getFullYear(), Today.getMonth(), Today.getDate());
if (arguments.length < 4)
{
DefaultDate = (Required) ? CurrentDate.formatted : '';
}
eval(DateName + '_Object=new calendarObject(\'' + DateName + '\',\'' + DateFormat + '\',\'' + DefaultDate + '\')');
if ((Required) || (arguments.length == 4))
{
var InitialStatus = '';
var InitialDate = eval(DateName + '_Object.picked.formatted');
}
else
{
var InitialStatus = ' style = "visibility : hidden"';
var InitialDate = '';
eval(DateName + '_Object.setPicked(' + Today.getFullYear() + ',' + Today.getMonth() + ',' + Today.getDate() + ')');
}
with (document)
{
writeln('');
for (var f = 0; f < forms.length; f++)
{
for (var e = 0; e < forms[f].elements.length; e++)
{
if (typeof forms[f].elements[e].type == 'string')
{
if ((forms[f].elements[e].type == 'hidden') && (forms[f].elements[e].name == DateName))
{
eval(DateName + '_Object.formNumber='+f);
break;
}
}
}
}
writeln('');
}
}
}