.
Id этого элемента является обязательным параметром настройки.
2. Необязательный контейнер для размещения выпадающего списка регионов, например:
. Должен быть пустым и располагаться внутри контейнера 1. Если не задан, то список будет динамически создан как последний дочерний элемент контейнера 1.
3. Необязательный контейнер для указания места вывода списка офисов, например:
. Должен быть пустым. Если не задан, то будет динамически создан сразу после контейнера 1.
4. Подключение данного скрипта или - в любом месте страницы, но до вызова любых методов еxat.officeList().
5. Вызов метода exat.officeList.config() - после описаных div'ов и подключения js-скрипта. Позволяет настроить механизм вывода списка офисов. Аргументы описаны далее.
Пример встраивания:
*/
/** Параметры настройки класса ExatOfficeList
* @access public
* @param cfg объект, может включать следующий набор полей:
* @param cfg.regionFieldEl - строка идентификатор div'а (или другого элемента-контейнера) html-блока списка регионов (городов)
* @param cfg.regionSelectEl - /необязательный параметр/ строка идентификатор div'а для вывода списка регионов
* @param cfg.officeListEl - /необязательный параметр/ строка идентификатор div'а для вывода списка офисов
* @param cfg.host - /необязательный параметр/ строка имени хоста для скачивания дополнительных ресурсов
* по умолчанию "exat.ru", можно указывать константу или подставлять document.location.hostname
* @param cfg.defRegionId - /необязательный параметр/ чисто-идентификатор региона показываемого по умолчанию
* @param cfg.getLocationGroupHtml - /необязательный параметр/ пользовательская функция отображения названия
* группы локайшенов (линий метро, районов города) См. пример реализации функции ниже.
* @param cfg.getOfficeHtml - /необязательный параметр/ пользовательская функция отображения офиса.
* См. пример реализации функции ниже.
*/
// Распаковщик данных
DataSet = function () {
var data = [];
var schema = {fields:[], keys:{}};
this.init = function(obj) {
schema.fields = obj.schema;
for (var i = 0, count = obj.schema.length; i < count; i++) {
schema.keys[obj.schema[i].name] = i;
}
data = obj.data;
}
this.getRowHash = function(row) {
if (!!data[row]) {
var result = {};
for (var i = 0, count = schema.fields.length; i < count; i++) {
result[schema.fields[i].name] = data[row][i];
}
return result;
}
}
this.getRowsHash = function(start, count) {
if (start == undefined) {
start = 0;
}
if (count == undefined) {
count = data.length;
}
var result = [];
for (var i = start, end = Math.min(start + count, data.length); i < end; i++) {
result.push(this.getRowHash(i));
}
return result;
}
}
// Конструктор
function ExatOfficeList(cfg) {
var _self = this;
this.config(cfg);
this.setColorLines();
this.loadTransport();
}
// Настройка
ExatOfficeList.prototype.config = function(cfg) {
var _self = this;
if (typeof cfg != 'object') {
return;
}
this.divRegionField = document.getElementById(cfg.regionFieldEl);
if (cfg.regionSelectEl) {
this.divRegionSelect = document.getElementById(cfg.regionSelectEl);
} else {
this.divRegionSelect = this.divRegionField.appendChild(document.createElement('div'));
}
this.regionSelectEl = document.createElement('select');
this.regionSelectEl.onchange=function(){_self.showOfficeList(this.value); _self.onChangeRegion(this.value);};
this.divRegionSelect.appendChild(this.regionSelectEl);
this.divRegionField.style.visibility = 'hidden';
if (cfg.officeListEl) {
this.divOfficeList = document.getElementById(cfg.officeListEl);
} else {
if (this.divRegionField.nextSibling) {
this.divOfficeList = this.divRegionField.parentNode.insertBefore(document.createElement('div'), this.divRegionField.nextSibling);
} else {
this.divOfficeList = this.divRegionField.parentNode.appendChild(document.createElement('div'));
}
}
this.host = (!cfg.host) ? "http://exat.ru" : cfg.host;
if (this.host.substring(0,7)!='http://') this.host = 'http://'+this.host;
this.divOfficeList.innerHTML = '

';
this.defRegionId = (cfg.defRegionId == undefined) ? 64 : cfg.defRegionId;
if(cfg.getLocationGroupHtml) this.getLocationGroupHtml = cfg.getLocationGroupHtml;
if(cfg.getOfficeHtml) this.getOfficeHtml = cfg.getOfficeHtml;
if(cfg.client_id) this.client_id = cfg.client_id;
}
// Добавление в урл строки client_id
ExatOfficeList.prototype.getUrlClientId = function(){
if(this.client_id)
return '&client_id='+this.client_id;
else
return '';
}
// Действия по готовности транспорта
ExatOfficeList.prototype.onTransportReady = function() {
this.loadRegionList();
this.showRegionList();
this.showOfficeList(this.defRegionId);
}
ExatOfficeList.prototype.onChangeRegion = function() {};
ExatOfficeList.prototype.reference = {locationGroups:{}, locations:{}};
ExatOfficeList.prototype.officeData = {};
// Подключение библиотеки транспорта
ExatOfficeList.prototype.loadTransport = function() {
if (!this.transportIsLoaded()) {
this.loadScript('/extlib/jr/mini/JsHttpRequest-script.js');
}
this.awaitTransport();
}
// Определяет,загружен ли транспорт
ExatOfficeList.prototype.transportIsLoaded = function() {
return (typeof JsHttpRequest != 'undefined' && !!JsHttpRequest.query);
}
// Цикл ожидания загрузки транспорта
ExatOfficeList.prototype.awaitTransport = function() {
if (!this.transportIsLoaded()) {
var _self = this;
setTimeout(function(){_self.awaitTransport()}, 200);
} else {
this.onTransportReady();
}
}
// Загрузка js-файла
ExatOfficeList.prototype.loadScript = function(url) {
jsEl = document.createElement('script');
jsEl.type = 'text/javascript';
jsEl.src = this.host + url;
jsEl.charset="windows-1251";
var headEl = document.getElementsByTagName('head')[0];
headEl.appendChild(jsEl);
}
// Загрузка списка регинов
ExatOfficeList.prototype.loadRegionList = function(url) {
this.loadScript('/touronline/?json=officelist_regionselect®ion='+this.defRegionId+this.getUrlClientId());
}
// отображение списка регионов (городов)
ExatOfficeList.prototype.showRegionList = function(){
var _self=this;
if(!this.regionList){
setTimeout(function(){_self.showRegionList();}, 500);
return false;
}
if (this.regionList.length == 0){
this.divRegionSelect.innerHTML='cписок пуст';
} else if(this.regionList.length==1) {
this.divRegionField.style.display='none';
//TODO Вывести название региона
//this.divRegionSelect.innerHTML = '';
} else {
var html = '';
for (var i=0; i
' ;
}
this.divOfficeList.innerHTML += this.getOfficesHtml(this.officeData[departure]);
return true;
} else {
// Данные по региону не готовы, загрузить
this.regionId = ((typeof departure)=='undefined') ? this.defRegionId : departure;
this.loadOfficeData(departure);
this.divOfficeList.innerHTML = '

Идет загрузка...';
// TODO Установка отправления в поисковой форме здесь не к месту
var searchDeparture = document.getElementById('exatDepartureCtrl');
if (searchDeparture){
for(var k=0; k
0){
this.OfficesGroupId = office.location_group_id;
office.location_group_name = (!!this.reference.locationGroups[office.location_group_id]) ? this.reference.locationGroups[office.location_group_id] : '';
office.location_group_name = office.location_group_name.replace('-', ' - ');
} else {
this.OfficesGroupId = 0;
office.location_group_name = "";
}
if(this.OfficesGroupId<10){
this.groupImgIndex="0"+this.OfficesGroupId;
} else {
this.groupImgIndex=this.OfficesGroupId;
}
if(this.OfficesGroupId!=0){
inner+=this.getLocationGroupHtml(office);
}
}
if(this.OfficesGroupId>0){
inner+=this.getOfficeHtml(office);
} else {
up+=this.getOfficeHtml(office);
}
}
return up+inner;
} else {
return "";//"Нет данных.";
}
}
// ссылка на описание агентства и всех его офисов
ExatOfficeList.prototype.getAgencyInfoHref = function(office){
return this.host+"/touronline/agency.php?office=" + office.office_id + "&portal=" + this.reference.portalId;
}
// оформление записи об одной группе локейшенов (линий метро, районов города)
ExatOfficeList.prototype.getLocationGroupHtml = function(office){
var html = '';
html += "
";
} else {
html += ">" + office.location_group_name;
}
html += "
";
return html;
}
// оформление записи об одном офисе
ExatOfficeList.prototype.getOfficeHtml = function(office){
var html='';
if (this.OfficesGroupId) {
html += "";
if (office.location_description == 'ст. метро') {
html += "

 ";
} else {
html += office.location_description + ' ';
}
html += office.location_name+"
";
}
html+="";
return html;
}