//Effect.DefaultOptions.duration = 0.3;
//Effect.DefaultOptions.queue = "end"

var pollSearchAlternatesClass = Class.create({
	initialize: function(so, url, url2, d) {
		this.so = so; // SearchOptions
		this.url = url; // url к executePollSearchAlternations
		this.url2 = url2; // url к executeIndex
		this.d = d; // div-container
		this.d_notice = this.d.down('div.notice');
		this.d_cont = this.d.down('div.container');
		this.t = this.so.time || null; // timestamp
		this.initTime = this.so.time || null; // timestamp
		this.p = null; // periodical
		this.i = 0; // число найденных совпадений после начала поиска
		this.startPeriodical.bind(this).delay(5);
		this.addRefreshHandler();
		
		Event.observe(window, 'focus', function(e) {
			this.startPeriodical();
			//window.console.log('start')
		}.bind(this));
		Event.observe(window, 'blur', function(e) {
			this.stopPeriodical();
			//window.console.log('stop')
		}.bind(this));
	},
	
	/**
	 * @private
	 */
	startPeriodical: function() {
		if (this.p) {
			this.p.stop();
		}
		var p = Object.clone(this.so);
		this.p = new Ajax.PeriodicalUpdater(false, this.url, {
			decay: 1.2,
			frequency: 20,
			parameters: Object.extend(p, {
				time: this.t,
				renderResults: 1
			}),
			onSuccess: function(r) {
				var r = r.responseText.evalJSON(), n = parseInt(r[0]);

				// если появились новые записи
				if (n > 0) {
					// обновить внутренее время
					//this.t = r[1];
					// обновить число результатов поиска
					this.updateAlternativeResultsCount(n);
					// отобразить контейнер с результатами поиска
					this.dispayAlternativeResultsNotice();
					this.restartPeriodical();
				}
				else {
					this.hideAlternativeResultsNotice();
					this.resetAlternativeResultsCounter();
				}
			}.bind(this)
		});
	},
	 
	stopPeriodical: function() {
		try {
			this.p.stop();
		}
		catch(e) {
//			alert(e)
		}
	},
	
	restartPeriodical: function() {
		this.stopPeriodical();
		this.startPeriodical.bind(this).delay(15);
	},
	
	refreshHandler: function() {
		new Ajax.Request(this.url2, {
			parameters: Object.extend(this.so, {
				time: this.initTime
			}),
			evalJS: false,
			onCreate: function() {
				this.hideAlternativeResultsNotice();
				this.resetAlternativeResultsCounter();
				this.stopPeriodical();
			}.bind(this),
			onComplete: function() {
			}.bind(this),
			onSuccess: function(r) {
				// в ответе мне понадобится обновленное время и собственно результаты к отображению
				var r = r.responseText;
				if (r.length > 0) {
					var e = (new Element('div')).update(r);
					this.t = parseInt(e.down('#alt-res-timestamp').innerHTML);
					// обновляем исходное время в конструкторе
					this.initTime = this.t;
					if (typeof this.t != 'number') {
						throw 'Error parsing response!';
					}
					e = null;
					// заполним новыми результатми поиска наш контейнер
					// отобразим полученные результаты
					this.dispayAlternativeResults(r);
					// нужно перезапустить periodical c новыми параметрами времени
					this.restartPeriodical();
				}
				else {
					this.restartPeriodical();
				}
			}.bind(this),
		});
	},
	
	addRefreshHandler: function() {
		if (typeof h != 'undefined') {
			this.d.down('a').stopObserving('click', h)
		}
		h = this.refreshHandler.bind(this);
		this.d.down('a').observe('click', h);
	},
	
	dispayAlternativeResultsNotice: function() {
		if (! this.d_notice.visible()) {
			new Effect.BlindDown(this.d_notice);
		}
	},
	
	hideAlternativeResultsNotice: function() {
		this.d_notice.hide();
//		new Effect.BlindUp(this.d_notice);
	},
	
	dispayAlternativeResults: function(r) {
		if (! this.d_cont.visible()) {
			this.d_cont.show();
		}
		var e = (new Element('div')).hide().update(r);
		Element.insert(this.d_cont, {'top': e});
		new Effect.BlindDown(e);
		var s = this.d.down('#search-alernatives-count');
		s.update(/*parseInt(s.innerHTML) + */this.i);
	},
	
	updateAlternativeResultsCount: function(n) {
		var i = parseInt(this.d_notice.down('span').innerHTML) || 0;
		this.i = n/* + i*/;
		this.d_notice.down('span').update(this.i);
	},
	
	resetAlternativeResultsCounter: function() {
		this.i = 0;
		this.d_notice.down('span').update(0);
	}
});

