var cld = {}; cld.ver = "cal 4.162 "; // calendarius.js // 2014 Jan 16 Th // ID: 1001 //
//meta http-equiv content-type charset=windows-1251
// *********************************** Calendar ***********************************
cld.c_imagesFolder = '/images/calendar/'; // путь к картинкам //
cld.c_tasksLanguage = 'ru'; // язык интерфейса //
// имена всплывающих слоев для календаря и ползунка //
cld.c_leeName_calendar = 'candarLee';
cld.c_leeName_bar = 'barLee';
cld.c_millInDay = 1000*60*60*24;
cld.c_dateFormat_std = 'dd.mm.yyyy';
cld.c_toShow_yes = true;
cld.c_toShow_no = false;
cld.c_barElemArray = ['barDateFrom', 'barDateTo', 'barDbg', 'barOk'];
cld.c_barElemWideArray_resid =
['ctrlNote', 'mess_fail', 'durMinLabel', 'durMaxLabel', 'brdValidat',
'hCtyValidat', 'hHtlValidat', 'prMaxLabel'];
cld.c_barElemWideArray_airtrip = ['ctrlNote', 'mess_fail', 'airTrpNValidat', 'airSCValidat', 'airDateT.img'];
cld.c_barElemWideArray_excurs = ['ctrlNote', 'mess_fail', 'trffTypValidat', 'prMaxLabel'];
cld.c_barElemWideArray_cruise = ['ctrlNote', 'mess_fail', 'trffTypValidat', 'prMaxLabel'];
cld.c_barElemWideArray = [
cld.c_barElemWideArray_resid, cld.c_barElemWideArray_airtrip,
cld.c_barElemWideArray_excurs, cld.c_barElemWideArray_cruise ];
// имена месяцев и т.п. //
var calendarNamesHash = new Array();
calendarNamesHash.ru = new Array();
calendarNamesHash.en = new Array();
calendarNamesHash.ru.month = ['Январь', 'Февраль', 'Март', 'Апрель', 'Май', 'Июнь', 'Июль', 'Август', 'Сентябрь', 'Октябрь', 'Ноябрь', 'Декабрь'];
calendarNamesHash.ru.monthShort = ['янв', 'фев', 'мар', 'апр', 'мая', 'июн', 'июл', 'авг', 'сен', 'окт', 'ноя', 'дек'];
calendarNamesHash.ru.weekday = ['Пн', 'Вт', 'Ср', 'Чт', 'Пт', 'Сб', 'Вс'];
calendarNamesHash.ru.today= 'сегодня';
calendarNamesHash.en.month = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
calendarNamesHash.en.monthShort = ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec'];
calendarNamesHash.en.weekday = ['M', 'T', 'W', 'T', 'F', 'S', 'S'];
calendarNamesHash.en.today= 'today';
var calendarNames = calendarNamesHash[ cld.c_tasksLanguage == 'en' ? 'en' : 'ru'];
// функция инициализации
var pixelSpacer = '
';
// интерфейсные функции
var closeCalendarTimeOut = 0;
var activeCalendarName = '';
var oldVisibility = 'visible';
cld.lastEvent = null;
// *********************************** DatePair ***********************************
cld.DatePair = function( argDateFrom, argDateTo, argPeriod ) {
this.dateFrom = argDateFrom;
this.dateTo = (argPeriod == 0 ? argDateFrom : argDateTo);
this.period = argPeriod;
};
cld.DatePair.prototype.toString = function() {
var dateFromStr = cld.lsCalendarTemp.getStrDateParam( this.dateFrom, cld.c_dateFormat_std );
var result;
//
if (this.period > 0 && this.dateTo != null) {
var dateToStr = cld.lsCalendarTemp.getStrDateParam( this.dateTo, cld.c_dateFormat_std );
result = dateFromStr.substring( 0, 5 ) + "-" + dateToStr;
}
else {
result = dateFromStr;
}
return result;
};
cld.DatePair.prototype.toStrJson = function() {
var dateF = ("" + this.dateFrom).substring( 4, 15 );
var dateT = ("" + this.dateTo ).substring( 4, 15 );
return "{ period: " + this.period + ", dateFrom: '" + dateF + "', dateTo: '" + dateT + "' }";
};
// *********************************** CalendarDate ***********************************
function CalendarDate() {
// члены
this.date = null;
this.state = 0; // =1 - туры есть, =2 - туры возможны, =0 - нет туров
this.CalendarDate = function( date, state ) {
this.date = date;
this.state = state;
};
return true;
};
// *********************************** LSCalendar ***********************************
function LSCalendar() {
// члены
this.date = null;
this.format = cld.c_dateFormat_std;
this.dateList = null;
return true;
};
// argDate - текст или объект Date
// state = 1,2 статус даты
LSCalendar.prototype.addDate = function() {
var args = this.addDate.arguments;
for ( var ix=0; ix < args.length-1; ix+=2 ) {
var argDate = args[ix];
var status = args[ix+1];
if (argDate==null || argDate=="") {
if ( this.dateList == null ) {
this.dateList= new Array(); // чтобы отличить реализацию с датами и без
}
} else if (typeof(argDate)=="string") {
if ( this.dateList == null ) {
this.dateList= new Array();
}
var objDate = this.str2Date( argDate);
var year = objDate.getYear();
if ( year < 1900 ) year += 1900;
if ( this.dateList[ year] == null) this.dateList[ year] = new Array();
if ( this.dateList[ year][ objDate.getMonth()] == null) this.dateList[ year][ objDate.getMonth()] = new Array();
this.dateList[ year][ objDate.getMonth()][objDate.getDate()] = status;
} else {
//alert( "_addDate: "+typeof(argDate));
}
}
return true;
};
LSCalendar.prototype.clearDates = function() {
this.dateList = null;
};
// Получить текущую дату, объект Date
LSCalendar.prototype.getDate = function() {
return this.date;
};
// Получить период между двумя датами
LSCalendar.prototype.getPeriod = function( argDateFrom, argDateTo ) {
var timeFrom = argDateFrom.getTime();
var timeTo = argDateTo.getTime();
var diffMillis = timeTo - timeFrom;
return Math.round( diffMillis / cld.c_millInDay );
};
// Получить хранимую у себя дату в строковом формате
LSCalendar.prototype.getStrDate = function() {
return this.getStrDateParam( this.date, this.format );
};
// Получить дату в строковом формате
LSCalendar.prototype.getStrDateParam = function( argDate, argFormat ) {
if (!argDate || !argFormat) {
return "";
}
else {
var Day = this.zeroFill( argDate.getDate() );
var Month = this.zeroFill( argDate.getMonth()+1 );
var Year = argDate.getFullYear();
var shortYear = argDate.getYear();
if (shortYear >= 2000) {
shortYear -= 2000;
} // перегибы на местах
else if (shortYear >= 100) {
shortYear -= 100;
} // перегибы на местах
shortYear = this.zeroFill(shortYear);
var result = "";
if (argFormat == 'dd-mm-yy' ) { result = Day+'-'+Month+'-'+shortYear; }
else if (argFormat == 'dd.mm.yy' ) { result = Day+'.'+Month+'.'+shortYear; }
else if (argFormat == 'yyyy-mm-dd') { result = Year+'-'+Month+'-'+Day; }
else if (argFormat == 'yyyy.mm.dd') { result = Year+'.'+Month+'.'+Day; }
else if (argFormat == 'dd.mm.yyyy') { result = Day+'.'+Month+'.'+Year; }
else { result = Day+'-'+Month+'-'+Year; }
return result;
}
};
// argDate - текст или объект Date
LSCalendar.prototype.setDate = function( argDate ) {
//
if (argDate == null || argDate=="") {
this.date = null;
}
else if (typeof(argDate) == "object") {
this.date = argDate;
}
else {
this.date = this.str2Date ? this.str2Date(argDate) : (new Date());
}
return true;
};
LSCalendar.prototype.setFormat = function( argFormat ) {
if (argFormat=='dd-mm-yy') { this.format='dd-mm-yy'; }
else if (argFormat=='dd.mm.yy') { this.format='dd.mm.yy'; }
else if (argFormat=='yyyy-mm-dd') { this.format='yyyy-mm-dd'; }
else if (argFormat=='yyyy.mm.dd') { this.format='yyyy.mm.dd'; }
else if (argFormat=='dd.mm.yyyy') { this.format='dd.mm.yyyy'; }
else { this.format='dd-mm-yyyy'; }
return true;
};
// Преобразовать строку в объект Date
LSCalendar.prototype.str2Date = function( argStr ) {
if (argStr) {
var RegYMDHIS = /^(\d{4})[-|.|\/](\d+)[-|.|\/](\d+)\s+(\d+):(\d+):(\d+)$/i; // yyyy-mm-dd hh:ii:ss
var RegDMYHIS = /^(\d+)[-|.|\/](\d+)[-|.|\/](\d{4})\s+(\d+):(\d+):(\d+)$/i; // dd-mm-yyyy hh:ii:ss
var RegYMD = /^(\d{4})[-|.|\/](\d+)[-|.|\/](\d+)$/i; // yyyy-mm-dd
var RegDMY = /^(\d+)[-|.|\/](\d+)[-|.|\/](\d{4})$/i; // dd-mm-yyyy
var RegDMY2 = /^(\d+)[-|.|\/](\d+)[-|.|\/](\d{2})$/i; // dd-mm-yy
var date = RegYMDHIS.exec(argStr);
if (date) { return (new Date(date[1],date[2]-1,date[3],date[4],date[5],date[6])); }
date = RegDMYHIS.exec(argStr);
if (date) { return (new Date(date[3],date[2]-1,date[1],date[4],date[5],date[6])); }
date = RegYMD.exec(argStr);
if (date) { return (new Date(date[1],date[2]-1,date[3])); }
date = RegDMY.exec(argStr);
if (date) { return (new Date(date[3],date[2]-1,date[1])); }
date = RegDMY2.exec(argStr);
if (date) {
var Year=Number(date[3]);
if (Year<50) { Year+=2000; }
else { Year+=1900; }
return (new Date(Year, (date[2]-1), date[1]));
}
}
return null;
};
// маленькая хитрая функция, проверки правильности формата даты //
LSCalendar.prototype.validate = function(argStr) {
return this.str2Date(argStr) != null;
};
// проверка правильности формата периода дат //
LSCalendar.prototype.validatePair = function( argStr) {
var result;
//
if (dateIsPeriod( argStr )) {
var dateFirstStr = getDateFirstFromPair( argStr );
var dateSecondStr = argStr.substring( 6, 16 );
result = (this.str2Date( dateFirstStr ) != null && this.str2Date( dateSecondStr ) != null);
}
else {
result = this.str2Date( argStr ) != null;
}
return result;
};
LSCalendar.prototype.zeroFill = function( value ) {
return (value < 10 ? '0' : '') + value;
};
// для совместимости
LSCalendar.prototype.SetDate = function( argValue ) { return this.setDate( argValue ); };
LSCalendar.prototype.SetFormat = function( argValue ) { return this.setFormat( argValue ); };
LSCalendar.prototype.Str2Date = function( argValue ) { return this.str2Date( argValue ); };
LSCalendar.prototype.Validate = function( argValue ) { return this.validate( argValue ); };
LSCalendar.prototype.ValidatePair = function( argValue ) { return this.validatePair( argValue ); };
// получить текущую дату календаря
function getCalendarDate( argElemId ) {
var result = LSCalendars[ argElemId ].getDate();
//
if (!result) {
return (new Date());
}
return result;
}
// выдать первыую дату из пары дат с учетом возможности перехода на новый год //
function getDateFirstFromPair( argDateStrPair ) {
var result;
//
if (dateIsPeriod( argDateStrPair )) {
var overNewYear = (argDateStrPair.substring(3, 5) == "12" && argDateStrPair.substring(9, 11) == "01");
//
if (overNewYear) {
var newYearStr = argDateStrPair.substring(12, 16);
var oldYearStr = "" + (parseInt( newYearStr, 10 )-1);
result = argDateStrPair.substring(0, 5) + '.' + oldYearStr;
}
else {
result = argDateStrPair.substring(0, 5) + argDateStrPair.substring(11, 16);
}
}
else {
result = argDateStrPair;
}
return result;
}
function getCalendarDateFirst( argElemId ) {
var elemDate = document.getElementById( argElemId );
var result;
//
if (!!elemDate) {
var dateStrDirty = elemDate.value;
var hasDateTo = dateIsPeriod( dateStrDirty );
var dateStrClear = (hasDateTo ? getDateFirstFromPair( dateStrDirty ) : dateStrDirty);
result = cld.lsCalendarTemp.str2Date( dateStrClear );
}
else {
result = new Date();
}
return result;
}
// получить текущую дату календаря и максимальную дату //
function getCalendarDatePair( argElemId ) {
var result;
//
var dateInputElem = document.getElementById( argElemId );
var dateStr = dateInputElem.value;
var dateFrom;
//
if (dateIsPeriod( dateStr )) {
var dateToStr = dateStr.substring(6, 16);
var dateFromStr = getDateFirstFromPair( dateStr );
dateFrom = cld.lsCalendarTemp.str2Date( dateFromStr );
var dateTo = cld.lsCalendarTemp.str2Date( dateToStr );
var period = cld.lsCalendarTemp.getPeriod( dateFrom, dateTo );
result = new cld.DatePair( dateFrom, dateTo, period );
}
else {
dateFrom = cld.lsCalendarTemp.str2Date( dateStr );
result = new cld.DatePair( dateFrom, dateFrom, 0 );
}
return result;
}
// переопределить дату календаря и на выводе
function setDateForCalendar(dayToSet, monthToSet, yearToSet) {
var dateToSet;
// что бы сохранить минуты, мы делаем так
if (!LSCalendars[activeCalendarName].getDate()) { dateToSet = new Date(); }
else { dateToSet = LSCalendars[activeCalendarName].getDate(); }
dateToSet.setFullYear(yearToSet);
dateToSet.setMonth(monthToSet,1);
dateToSet.setDate(dayToSet);
LSCalendars[activeCalendarName].setDate(dateToSet);
setInputByLSCalendar(activeCalendarName);
// закрываем календарь
hideCalendar();
}
// переопределить дату календаря из строки
function setCalendarDateByStr(name, strDate) {
closeCalendarTimeOut = 0; // важно
//
if (strDate == null || strDate == "") { // если пустая строка
LSCalendars[name].setDate( null );
return true;
}
else {
if (dateIsPeriod( strDate )) {
if (!cld.lsCalendarTemp.validatePair( strDate )) {
alert("Неверный формат дат в диапазоне - " + strDate);
setInputByLSCalendar(name);
return false;
}
else {
var dateFirstStr = getDateFirstFromPair( strDate );
LSCalendars[name].setDate( dateFirstStr );
setInputByLSCalendar(name);
return true;
}
}
else {
if (!cld.lsCalendarTemp.validate( strDate )) {
alert("Неверный формат даты - " + strDate);
setInputByLSCalendar(name);
return false;
}
else {
LSCalendars[name].setDate(strDate);
setInputByLSCalendar(name);
return true;
}
}
}
}
function dateIsPeriod( argDateStr ) {
return argDateStr != null && argDateStr.length == 16 && argDateStr.indexOf('-') == 5;
}
// синхронизирует текущее значение календаря и форму ввода //
// и явно вызывает обработчик события onchange //
function setInputByLSCalendar(name) {
// этот метод может переопределяться в модуле erc.calendar.js //
// чтобы нажатие на дату приводило к эффекту, //
// нужному для дизайн-элемента exchangeRate //
if (LSCalendars[name].setInput != null) {
return LSCalendars[name].setInput( name );
}
var inpCalElem = document.getElementsByName(name)[0];
var oldCalDate = inpCalElem.value;
var newCalDate = LSCalendars[name].getStrDate();
inpCalElem.value = newCalDate;
inpCalElem["title"] = newCalDate;
//
if ((oldCalDate != newCalDate) && inpCalElem.onchange) {
inpCalElem.onchange();
}
//document.getElementsByName(name)[0].value=LSCalendars[name].getStrDate();
return true;
}
// задать сегодняшнюю дату для значений календаря
function setTodayFromCalendar() {
var date=new Date();
setDateForCalendar(date.getDate(),date.getMonth(),date.getFullYear());
}
// вычислить элементы select и div под слоем и скрыть или показать
function changeElVis( argMyVisibility, argLeerName ) {
var calLeer = document.getElementById( argLeerName );
// вычисляем где именно должен быть этот календарь.
var calPosition = new getElementPosition(calLeer);
if ((argMyVisibility=='hide') || (argMyVisibility=='hidden')) {
argMyVisibility = 'hidden';
if ( oldVisibility == argMyVisibility ) {
changeElVis( 'visible', argLeerName ); // восстановить скрытые в предыдущем вызове
}
} else {
argMyVisibility = 'visible';
//use old calXXXX values
}
var calTop = calPosition.y;
var calLeft = calPosition.x;
var calBottom = calTop + calLeer.clientHeight;
var calRight = calLeft + calLeer.clientWidth;
oldVisibility = argMyVisibility;
var c_tags = ['select','input','iframe','object'];
for (var t=0; t= argCalLeft) || // поле левее календаря и календарь задевает поле //
(elemLeft >= argCalLeft) && (elemRight <= argCalRight) || // поле уже календаря и слева и справа //
(elemLeft <= argCalRight) && (elemRight >= argCalRight)) { // поле шире календаря и слева и справа //
if ((elemTop <= argCalTop) && (elemBottom >= argCalTop) ||
(elemTop >= argCalTop) && (elemBottom <= argCalBottom) ||
(elemTop <= argCalBottom) && (elemBottom >= argCalBottom))
{
if (argMyVisibility == 'hidden') {
if (!!tempElem.oldVis) {
tempElem.oldVis = (!!tempElem.style.visibility ? tempElem.style.visibility : tempElem.oldVis);
}
else {
tempElem.oldVis = 'visible';
}
tempElem.style.visibility = argMyVisibility;
}
else { // 'visible'
if ((!!tempElem.oldVis) && (tempElem.oldVis != argMyVisibility)) {
tempElem.style.visibility = tempElem.oldVis;
}
else {
tempElem.style.visibility = argMyVisibility;
}
}
}
}
}
}
function showCalendarForElement(elemName, evt, defaultDate, isLeft) {
var calPtr = document.getElementById(elemName + 'Ptr');
if (calPtr) {
// показывает календарь в слое (создает слой, если необходимо)
var leerName = cld.c_leeName_calendar;
var calLeer = document.getElementById( leerName );
if (!calLeer) {
calLeer = document.createElement('div');
calLeer.id = leerName;
calLeer.style.cssFloat = 'inherit';
document.getElementsByTagName('body')[0].appendChild(calLeer);
}
// проверяем показан ли слой, если да - скрываем
if (calLeer.style.visibility == 'visible' && activeCalendarName == elemName) {
calLeer.style.visibility = 'hidden';
changeElVis('visible', leerName);
}
else {
activeCalendarName = elemName;
// скрываем слой
calLeer.style.visibility = 'hidden';
// вычисляем где именно должен быть этот календарь.
var calPosition = new getElementPosition(calPtr);
// заполняем нужным кодом...
// смотрим какая дата нас интересует
var currDate = getCalendarDate( elemName );
// дата по умолчанию, применяется если по умолчанию сегодня
var CDate=currDate.getDate()+"-"+currDate.getMonth()+"-"+currDate.getFullYear();
var TDate=(new Date()).getDate()+"-"+(new Date()).getMonth()+"-"+(new Date()).getFullYear();
if (CDate==TDate) {
if (typeof(defaultDate) == "object" && defaultDate) {
currDate=defaultDate;
}
}
// собственно вызываем код
calLeer.innerHTML = calendarHTML(currDate.getMonth(), currDate.getFullYear(), currDate);
// ставим слой на место
if ( isLeft ) {
calLeer.style.left = '' + calPosition.x-calLeer.offsetWidth + 'px';
calLeer.style.top = '' + calPosition.y + 'px';
}
else {
calLeer.style.left = '' + calPosition.x + 'px';
calLeer.style.top = '' + calPosition.y + 'px';
// calLeer.style.left = calPosition.x - calLeer.offsetWidth/3*2;
}
calLeer.style.position = 'absolute';
calLeer.style.zIndex = 10000;
calLeer.style.opacity = .99;
// показываем календарик
calLeer.style.visibility = 'visible';
changeElVis('hidden', leerName);
// наконец, прекращаем баблинг (может, кто-то открыл без event'а)
if (evt) {
evt.cancelBubble = true;
}
// и ставим свой обработчик на клик на календаре (чтобы не скрывался)
addEvent(calLeer, 'click', calendarClick);
// и на mouseout (чтобы скрывался, но через некоторое время ;-)
addEvent(calLeer, 'mouseover', calendarMouseOver);
addEvent(calLeer, 'mouseout', calendarMouseOut);
}
}
}
function showCalendarPlus( argElemName, argEvent ) {
var calPtr = document.getElementById( argElemName + 'Ptr');
//
if (!!calPtr) {
var leerName = cld.c_leeName_calendar;
// показывает календарь в слое (создает слой, если необходимо) //
var calLeer = document.getElementById( leerName );
//
if (!calLeer) {
calLeer = document.createElement('div');
calLeer.id = leerName;
calLeer.style.cssFloat = 'inherit';
document.getElementsByTagName('body')[0].appendChild(calLeer);
}
// проверяем показан ли слой, если да - скрываем //
if (calLeer.style.visibility == 'visible' && activeCalendarName == argElemName) {
calLeer.style.visibility = 'hidden';
changeElVis('visible', leerName);
}
else {
activeCalendarName = argElemName;
// скрываем слой
calLeer.style.visibility = 'hidden';
// вычисляем где именно должен быть этот календарь. //
var calPosition = new getElementPositionTrace( calPtr );
// заполняем нужным кодом... //
// смотрим какая дата нас интересует //
var currDate = getCalendarDateFirst( argElemName );
// собственно вызываем код //
calLeer.innerHTML = calendarHTML(currDate.getMonth(), currDate.getFullYear(), currDate);
// ставим слой на место //
calLeer.style.left = '' + calPosition.x + 'px';
calLeer.style.top = '' + calPosition.y + 'px';
calLeer.style.position = 'absolute';
calLeer.style.zIndex = 10000;
calLeer.style.opacity = .99;
// показываем календарик //
calLeer.style.visibility = 'visible';
changeElVis('hidden', leerName);
// наконец, прекращаем баблинг (может, кто-то открыл без event'а) //
if (argEvent) {
argEvent.cancelBubble = true;
}
// и ставим свой обработчик на клик на календаре (чтобы не скрывался) //
addEvent(calLeer, 'click', calendarClick);
// и на mouseout (чтобы скрывался, но через некоторое время ;-)
addEvent(calLeer, 'mouseover', calendarMouseOver);
addEvent(calLeer, 'mouseout', calendarMouseOut);
}
}
return false;
}
function showCalendarBar( argElemName, argFormWidth, argFormType, argEvent ) {
var barElemName = argElemName + "Bar";
var barPtr = document.getElementById( barElemName );
//
if (!!barPtr) {
var leerName = cld.c_leeName_bar;
// показывает ползунок в слое (создает слой, если необходимо) //
var barLeer = document.getElementById( leerName );
//
if (!barLeer) {
barLeer = document.createElement('div');
barLeer.id = leerName;
barLeer.style.cssFloat = 'inherit';
document.getElementsByTagName('body')[0].appendChild( barLeer );
}
// проверяем показан ли слой, если да - скрываем //
if (barLeer.style.visibility == 'visible' && activeCalendarName == barElemName) {
calendarBarOpenHide( barLeer, leerName, cld.c_toShow_no, argFormWidth, argFormType );
}
else {
activeCalendarName = barElemName;
// скрываем слой
barLeer.style.visibility = 'hidden';
// вычисляем где именно должен быть этот календарь. //
var barPosition = new getElementPositionTrace( barPtr );
// заполняем нужным кодом... //
// смотрим какая дата нас интересует //
var currDatePair = getCalendarDatePair( argElemName );
// собственно вызываем код //
barLeer.innerHTML = calendarBarHTML( argElemName, argFormWidth, argFormType, currDatePair );
// ставим слой на место //
barLeer.style.left = '' + barPosition.x + 'px';
barLeer.style.top = '' + barPosition.y + 'px';
barLeer.style.position = 'absolute';
// показываем ползунок //
calendarBarOpenHide( barLeer, leerName, cld.c_toShow_yes, argFormWidth, argFormType );
// наконец, прекращаем баблинг (может, кто-то открыл без event'а) //
if (argEvent) {
argEvent.cancelBubble = true;
}
// и ставим свой обработчик на клик на ползунке (чтобы не скрывался) //
addEvent(barLeer, 'click', calendarClick);
// и на mouseout (чтобы скрывался, но через некоторое время ;-)
addEvent(barLeer, 'mouseover', calendarMouseOver);
addEvent(barLeer, 'mouseout', calendarMouseOut);
}
}
return false;
}
function calendarBarOpenHide( argBarLeer, argLeerName, argToShow, argFormWidth, argFormType ) {
var normalOp = (argToShow ? "visible" : "hidden");
var backOp = (argToShow ? "hidden" : "visible");
argBarLeer.style.visibility = normalOp;
changeElVis( backOp, argLeerName );
changeElVisArray( cld.c_barElemArray, normalOp );
//
if (argFormWidth == "wide") {
var barElemWideArray = cld.c_barElemWideArray[ argFormType-1 ];
changeElVisArray( barElemWideArray, backOp );
}
}
function calendarBarHTML( argElemName, argFormWidth, argFormType, argDatePair ) {
var dateFromStr = cld.lsCalendarTemp.getStrDateParam( argDatePair.dateFrom, cld.lsCalendarTemp.format );
var dateToStr = cld.lsCalendarTemp.getStrDateParam( argDatePair.dateTo, cld.lsCalendarTemp.format );
var periodStr = "" + argDatePair.period;
var formWidth = "\"" + argFormWidth + "\"";
var barMarks = calendarBarMarks();
var arrowPos = (argDatePair.period > 0 ? "" + ((argDatePair.period * 25)) + "px" : "0" );
var str =
"\n";
return str;
}
function calendarBarMarks() {
var dates = "0
\n";
var marks = "";
//
for (var n=1; n<9; n++) {
if (n < 8) {
dates += "+" + n + "
\n";
}
marks += "|
\n";
}
return dates + marks;
}
function calendarClick(e) {
var evt = (e)? e : window.event;
evt.cancelBubble = true;
}
function calendarMouseOver(e) {
if (closeCalendarTimeOut) {
clearTimeout(closeCalendarTimeOut);
closeCalendarTimeOut = 0;
}
cld.lastEvent = e;
}
function calendarMouseOut(e) {
if (closeCalendarTimeOut) {
clearTimeout(closeCalendarTimeOut);
}
cld.lastEvent = e;
//closeCalendarTimeOut = setTimeout('hideCalendar()', 5000);
}
function hideCalendar() {
var calLeer = document.getElementById( cld.c_leeName_calendar );
if (calLeer) {
changeElVis( 'show', cld.c_leeName_calendar );
calLeer.style.visibility = 'hidden';
}
closeCalendarTimeOut = 0;
}
function switchMonthTo( month, year, argLeerName ) {
var calLeer = document.getElementById( argLeerName );
if (calLeer) {
// заполняем нужным кодом...
// смотрим какая дата нас интересует
var currDate = getCalendarDate(activeCalendarName);
// собственно вызываем код
//changeElVis('show', argLeerName); // размер календаря может измениться, поэтому сначала покажем все что было скрыто
calLeer.innerHTML = calendarHTML(month, year, currDate);
//changeElVis('hide', argLeerName ); // а затем опять скроем
}
}
function calendarHTML(month, year, currDate) {
// смотрим этот ли месяц показываем
var isThisMonth = (currDate)? (currDate.getMonth() == month && currDate.getFullYear() == year) : false;
// генерирует html-код для указанного месяца
// устанавливаем месяц, который будем рисовать
var drawMonth = new Date();
drawMonth.setMonth(month, 1);
drawMonth.setYear(year);
drawMonth.setDate(1);
// переменные для кнопок навигации по месяцам/годам
var thisMonth = drawMonth.getMonth();
var nextMonth = (thisMonth == 11)? 0 : thisMonth + 1;
var prevMonth = (thisMonth == 0)? 11 : thisMonth - 1;
var thisYear = drawMonth.getFullYear();
var nextYear = thisYear + 1;
var prevYear = thisYear - 1;
var nextMonthYear = (thisMonth == 11)? thisYear + 1 : thisYear;
var prevMonthYear = (thisMonth == 0)? thisYear - 1 : thisYear;
var leeName = '\'' + cld.c_leeName_calendar + '\'';
// запихиваем в строку весь код - открываем таблицы...
// #D7D7D7
var calendarCode = '';
calendarCode += '';
// здесь указываем клик на прошлый год
calendarCode += ' | ';
// текущий (показываемый) год
calendarCode += '' + thisYear + ' | ';
// клик на следующий год
calendarCode += ' | ';
// клик на предыдущий месяц
calendarCode += ' | ';
// текущий месяц
calendarCode += '' + calendarNames.month[thisMonth] + ' | ';
// клик на следующий месяц
calendarCode += ' | ';
calendarCode += ' |
';
// начинаем таблицу самого месяца #D7D7D7
calendarCode += '' +
'' +
'';
calendarCode += '
|
| ';
for (var k = 0; k < calendarNames.weekday.length; k++) {
//var styleClass = (k < calendarNames.weekday.length - 1)? 'whiteCell' : 'sundayCell';
calendarCode += '' + calendarNames.weekday[k] + ' | ';
}
calendarCode += '
|
| ';
// сам месяц
calendarCode += '
|
| ';
// рисуем пустые ячейки если нужно...
var daysToStart = (drawMonth.getDay() == 0)? 7 : drawMonth.getDay();
for (var d = 0; d < daysToStart - 1; d++) {
calendarCode += '
| ';
}
if ( year < 1900 ) year += 1900;
var haveDays = activeCalendarName && LSCalendars[ activeCalendarName].dateList != null;
var havePossible = false;
var haveTour = false;
var monthDays = haveDays ?
LSCalendars[ activeCalendarName].dateList[ year] ?
LSCalendars[ activeCalendarName].dateList[ year][ month] ?
LSCalendars[ activeCalendarName].dateList[ year][ month] : null
: null
: null;
// собственно циферки
for (var i = 1; i < 33; i++) {
drawMonth.setDate(i);
var onClick = '';
var styleClassTmp =
isThisMonth && i == currDate.getDate() ?
'blackCell' :
(drawMonth.getDay() == 0) ? 'sundayCell' : 'whiteCell';
var state = monthDays != null ? monthDays[ i] : 0;
if ( state == 1 ) {
// временно разрешим заказывать
//onClick = 'onClick="setDateForCalendar(' + i + ', ' + month + ', ' + year + ');" style="cursor: pointer; cursor: hand;"';
styleClassTmp+='-e';
havePossible = true;
} else if ( state == 2 ) {
onClick = 'onClick="setDateForCalendar(' + i + ', ' + month + ', ' + year + ');" style="cursor: pointer; cursor: hand;"';
styleClassTmp+='-y';
haveTour = true;
} else if ( ! haveDays ) {
onClick = 'onClick="setDateForCalendar(' + i + ', ' + month + ', ' + year + ');" style="cursor: pointer; cursor: hand;"';
}
if (drawMonth.getMonth() == thisMonth) {
calendarCode += '' + i + ' | ';
} else {
break;
}
if (drawMonth.getDay() == 0) {
calendarCode +=
'
|
| ' +
'
|
| ';
}
}
// опять рисуем пустые ячейки
if (drawMonth.getDay() != 1) {
var daysToEnd = 8 - ((drawMonth.getDay() == 0)? 7 : drawMonth.getDay());
for (var dd = 0; dd < daysToEnd; dd++) {
calendarCode += '
| ';
}
}
calendarCode += '
|
| |
';
// ссылка на сегодня
calendarCode += ''+calendarNames.today+' |
';
// легенда
if ( haveDays ) {
calendarCode += '';
if ( haveTour ) {
calendarCode += '_ | - есть тур на эту дату |
';
}
if ( havePossible ) {
calendarCode += '_ | - есть при других значениях: |
';
calendarCode += ' | города вылета, или типа тарифа |
';
}
if ( ! haveTour && ! havePossible ) {
calendarCode += ' нет туров на этот месяц. |
';
}
calendarCode += '
';
}
// конец
calendarCode += '
';
return calendarCode;
}
function getElementPosition( elemPtr ) {
var posX = elemPtr.offsetLeft;
var posY = elemPtr.offsetTop;
while (elemPtr.offsetParent != null) {
elemPtr = elemPtr.offsetParent;
posX += elemPtr.offsetLeft;
posY += elemPtr.offsetTop;
}
this.x = posX;
this.y = posY;
return this;
}
function getElementPositionTrace( elemPtr ) {
var posX = elemPtr.offsetLeft;
var posY = elemPtr.offsetTop;
while (elemPtr.offsetParent != null) {
elemPtr = elemPtr.offsetParent;
posX += elemPtr.offsetLeft;
posY += elemPtr.offsetTop;
}
this.x = posX;
this.y = posY;
return this;
}
function addEvent(Obj, eventType, eventFunc) {
if (Obj.addEventListener) { Obj.addEventListener(eventType, eventFunc, false); }
else if (Obj.attachEvent) { Obj.attachEvent('on'+eventType, eventFunc); }
else {
// что делать если ни то ни другое не поддерживается
}
}
function calendar(name, Date) {
LSCalendars[name]=new LSCalendar();
LSCalendars[name].setDate(Date);
// Вставляет HTML-код с необходимыми полями...
document.write('');
}
addEvent(document, 'click', hideCalendar);
addEvent(window, 'resize', hideCalendar);
//
cld.debShow = function() {
alert( cld.deb );
cld.deb = cld.ver;
};
// массив объектов LSCalendar для каждого календаря
var LSCalendars = new Array();
// временный объект чтобы можно было вызывать методы для разных нужд
cld.lsCalendarTemp = new LSCalendar();
cld.deb = cld.ver;