Files

215 lines
8.3 KiB
JavaScript

/*
* компонент поиска Я-пользователя
*/
Friends.YauserSearch = function(element, params) {
if (arguments.length > 0) {
this.init.apply(this, arguments);
}
};
Friends.YauserSearch.prototype = {
init: function(element, params) {
/** control container. */
this.control = element;
this.control.YauserSearchControl = this;
this.params = params;
this.searchError_b = y5.Dom.getDescendants(this.control, 'b', 'b-note-attention')[0];
this.search_input = y5.Dom.getDescendant(this.control, 'input', 'text');
this.usersList_table = y5.Dom.getDescendant(this.control, 'table', 'b-write-users-list');
this.search_btn = y5.Dom.getDescendants(this.control, 'input', 'submit')[0];
this.myFriends_link = y5.Dom.getDescendant(this.control, 'a', 'my-friends');
this.friendControl = new Friends.FriendControl(this.control);
this.search_btn.disabled = false;
this.INVALID_SEARCH_TEXT = 'Логин или имя пользователя должны быть заданы';
// ajax-метод поиска пользователя
this.ajaxMethod_search = 'ajax/search_users_by_name_not_me';
// ajax-метод получения определенного списка пользовтаелей
if (this.params) {
this.ajaxMethod_get = 'ajax/' + this.params.ajaxMethod_get;
}
this.setEvents();
},
// навешиваем обработчики событий
setEvents: function() {
var self = this;
$(this.control).find(".my-friends").die("click.yausersearch").live("click.yausersearch", function(e){
self.hideErrorMessages();
self.resetSearchResults();
e.preventDefault();
self.friendControl.setStatusMessage('Идёт загрузка пользователей<br /><img src="' + g_globals.img_base + 'bar.gif" alt=""/>');
y5.Events.notify('y5:usersAreFound', self.friendControl, true);
if (self.friendsHTML) {
self.onFriendsSearch(self.friendsHTML);
return;
}
var _self = self;
// функция на успех запроса
function responseOK(request, trace) {
_self.onFriendsSearch(request.html);
_self.friendsHTML = request.html; // запоминаем список друзей
}
// функция на успех запроса
function responseError(trace) {
self.friendControl.setStatusMessage("ошибка " + trace);
}
var url = friendsURL(self.ajaxMethod_get);
// загружаем список друзей
jQuery.ajax({
url: url,
dataType: 'json',
success: responseOK,
error: responseError
});
});
y5.ShortCut.down([{key: y5.ShortCut.ENTER}],
function(e) {
// dispatch'им click по кнопке 'Найти'
return new y5.Event('click', this.search_btn, true);
},
this.search_input, {checkTarget: false, context: this});
},
// при поиске друзей
onFriendsSearch: function(html) {
this.fillUsers_select(html);
if (this.users_select.options.length === 0){
this.friendControl.setStatusMessage("никого не найдено");
return;
}
this.users_select.selectedIndex = 0;
this.friendControl.setStatusMessage("&#8592;&#160;выберите человека");
this.friendControl.list = this.users_select;
this.friendControl.showUserInfo();
y5.Events.notify('y5:userIsSelected', this.friendControl, true);
new y5.AEventListener('change', function() {
this.friendControl.list = this.users_select;
this.friendControl.showUserInfo();
y5.Events.notify('y5:userIsSelected', this.friendControl, true);
}, this.users_select, true, this);
},
// заполняем список найденных пользователей
fillUsers_select: function(html) {
this.users_select = y5.Dom.getDescendant(this.control, 'td', 'list').getElementsByTagName('select')[0];
var parent = this.users_select.parentNode;
//&apos; ставится стандартной xscript'овой функцией xmlescape
//в IE6 такой html вызывает ошибку, вот замена на ucp-шное значение выручает
html = html.replace(/&apos;/g,'\x27');
parent.innerHTML = html;
this.users_select = parent.firstChild;
},
// при поиске пользователя
onSearch: function() {
this.resetSearchResults();
if (!this.isYauserLogin()) {
this.showErrorMessage(this.searchError_b, this.INVALID_SEARCH_TEXT);
return false;
}
y5.Events.notify('y5:usersAreFound', this.friendControl, true);
return true;
},
// проверяем, задана ли строка поиска
isYauserLogin: function() {
return !y5.Strings.isVoid(this.search_input.value);
},
// показываем сообщения об ошибках
showErrorMessage: function (errorNote, msg) {
if (msg) {
errorNote.innerHTML = msg;
}
y5.Classes.remove(errorNote, 'i-hidden');
},
// прячем сообщения об ошибках
hideErrorMessages: function(errorNote) {
y5.Classes.add(this.searchError_b, 'i-hidden');
y5.Events.notify('y5:hideErrorMessages', this.friendControl, true);
},
// сбрасываем результаты поиска
resetSearchResults: function() {
this.hideErrorMessages();
y5.Events.notify('y5:resetSearchResults', this.friendControl, true);
},
// инициализируем список найденных пользователей
initUsers_select: function() {
this.users_select = y5.Dom.getDescendant(this.control, 'td', 'list').getElementsByTagName('select')[0];
new y5.AEventListener('change', function() {
y5.Events.notify('y5:userIsSelected', this.friendControl, true);
}, this.users_select, true, this);
}
};
y5.require (
['Dom', 'Events', 'ShortCuts', '{Friends}.FriendControl'],
function() {
y5.loaded('{Friends}.YauserSearch');
Friends.FriendControl.prototype.searchResponseOKOld = Friends.FriendControl.prototype.searchResponseOK;
Friends.FriendControl.prototype.searchResponseOK = function (request, trace) {
var _this = trace.parent;
_this.searchResponseOKOld(request, trace);
if (_this.list.length) {
_this.list.selectedIndex = 0;
_this.showUserInfo();
_this.control.YauserSearchControl.initUsers_select();
y5.Events.notify('y5:userIsSelected', _this.control.YauserSearchControl.friendControl, true);
}
};
Friends.FriendControl.prototype.searchResponseError = function (trace) {
var _this = trace.parent;
_this.setStatusMessage("ошбика " + trace);
};
Friends.FriendControl.prototype.onSearch = function() {
if (!this.control.YauserSearchControl.onSearch()) {
return false;
}
var _this = this;
this.setStatusMessage('Идёт загрузка пользователей<br /><img src="' + g_globals.img_base + 'bar.gif" alt=""/>');
var fields = getByTagName("input", this.submit.form);
var url = friendsURL(this.control.YauserSearchControl.ajaxMethod_search, y5.FormCollector.collectTags(this.control));
// загружаем список пользователей
jQuery.ajax({
url: url,
dataType: "json",
success: function(response){
_this.searchResponseOK(response, {parent:_this} );
},
error: function(response){
_this.searchResponseError(response, {parent:_this} );
}
});
return false;
};
}
);