var Search4 = Class.create({
	
	initialize: function(prefixes)
	{
		this._prefixes = prefixes; // inicjalizowane z htmla
		this._autocompleters = {};
		this._elements = {};
		this._observers = {
			'cel': [ 'wtorny', 'lokale' ],
			'przetarg': [ 'dzialki' ],
			'typwrapper': [ 'dzialki' ] // do szukarki search_temp
		};
		this._specjalne = {sync: {element: $('s4_container'), instances: this._prefixes.length, counter: 0}};

		// do boxów regionów/miejscowości
		this._region = {};
		this._miejscowosc = {};
		this._dzielnica = {};

		this._initElements();
		this._initAutocompleter();
		this._initHintText();
		this._initHints();
		this._initObservers();
		this._initWiecej();
		this._initSpecjalne();
	},

	_initHintText: function()
	{
		this._hintText = Lang.region_miasto_lub_dzielnica;
	},

	/**
	 * Metoda uruchamia hinty na pustych lokalizacjach
	 */
	_initHints: function()
	{
		var _this = this;
		this._prefixes.each(function(prefix) {
			if ($F(_this._elements[prefix]['lokalizacja']) == '') {
				_this._elements[prefix]['lokalizacja'].addClassName('s4_input_hint');
				_this._elements[prefix]['lokalizacja'].setValue(_this._hintText);
			}
		});
	},

	/**
	 * Metoda inicjalizuje autocompleter
	 */
	_initAutocompleter: function()
	{
		var _this = this;
		this._prefixes.each(function(prefix) {
			_this._autocompleters[prefix] = new Ajax.Autocompleter(
				_this._elements[prefix]['lokalizacja'],
				_this._elements[prefix]['autocompleter'],
				'/search4,ajax-autocompleter', {
					paramName: 'lokalizacja',
					indicator: _this._elements[prefix]['indicator'],
					frequency: 0.2,
					callback: _this.callback,
					onShow: _this.onShow,
					onHide: _this.onHide,
					minChars: 1
				}
			);
		});
	},

	/**
	 * Metoda uzupełnia automatycznie tablicę elements
	 */
	_initElements: function()
	{
		var _this = this;
		this._prefixes.each(function(prefix) {
			_this._elements[prefix] = {};

			$$('#s4_' + prefix + '_box_container *').each(function(element) {
				if (element.id != '') {
					var match = (new RegExp('^s4_([a-z]+)_(.+)')).exec(element.id);
					if (typeof match[2] != 'undefined')
						_this._elements[prefix][match[2]] = $(element);
				}
			});

		});

		_this._elements['box_lokalizacja'] = $('s4_box_lokalizacja');
		_this._elements['box_lokalizacja_iframe'] = $('s4_box_lokalizacja_iframe');
	},

	/**
	 * Metoda inicjalizuje link 'wiecej' i boxy regionów/miast
	 */
	_initWiecej: function()
	{
		this._prefixes.each(function(prefix) {
			this._region[prefix] = $F(this._elements[prefix]['region']);

			var miejscowosc = $F(this._elements[prefix]['miejscowosc']);
			this._miejscowosc[prefix] = miejscowosc != "" ? miejscowosc.split('.') : [];
			var dzielnica = $F(this._elements[prefix]['dzielnica']);
			this._dzielnica[prefix] = dzielnica != "" ? dzielnica.split('.') : [];

			this._setLokalizacjaWiecej(prefix);
		}, this);
	},

	/**
	 * Metoda odpala observery
	 */
	_initObservers: function()
	{
		var _this = this;
		this._prefixes.each(function(prefix) {
			Event.observe(_this._elements[prefix]['lokalizacja'], 'focus', function(event) {
				_this._lokalizacjaClick(_this._getPrefix($(Event.findElement(event)).id));
			});
			Event.observe(_this._elements[prefix]['lokalizacja'], 'blur', function(event) {
				_this._lokalizacjaBlur(_this._getPrefix($(Event.findElement(event)).id));
			});

			Event.observe(_this._elements[prefix]['form'], 'submit', function(event) {
				_this._formSubmit(_this._getPrefix($(Event.findElement(event)).id));
			});

			Event.observe(_this._elements[prefix]['typ'], 'change', function(event) {
				_this._resetLokalizacjaWiecej(prefix);
			});

			if (_this._observers['cel'].inArray(prefix)) {
				Event.observe(_this._elements[prefix]['cel'], 'change', function(event) {
					_this._resetLokalizacjaWiecej(prefix);
					_this._toggleCenaCzynsz(_this._getPrefix($(Event.findElement(event)).id));
				});
				Common.Event.fire(_this._elements[prefix]['cel'], 'change');
			}
		});
	},

	/**
	 * Metoda ustawia oferty specjalne
	 */
	_initSpecjalne: function()
	{
		if (typeof search4Specjalne == 'undefined')
			return;

		var delay = 0;
		this._prefixes.each(function(prefix) {
			this._specjalne[prefix] = new Specjalne(
					search4Specjalne[prefix]['idList'], 
					search4Specjalne[prefix]['options'],
					$('s4_' + prefix + '_specjalna1'),
					$('s4_' + prefix + '_specjalna2'),
					'/index,ajax-specjalne-search',
					delay += 0.5,
					this._specjalne['sync']
			);
			this._specjalne[prefix].run();
		}, this);

	},

	/**
	 * Pomocnicza funkcja, zwraca prefix z id elementu
	 */
	_getPrefix: function(id)
	{
		return (new RegExp('^s4_([a-z]+)_')).exec(id)[1];
	},

	/**
	 * Po kliknięciu w lokalizację metoda rozwija domyślną listę miejscowości
	 */
	_lokalizacjaClick: function(prefix)
	{
		var input = this._elements[prefix]['lokalizacja'];

		if (input.hasClassName('s4_input_hint')) {
			input.setValue('');
			input.removeClassName('s4_input_hint');
		}

		if (input.getValue().empty()) {
			this._autocompleters[prefix].activate();
		}
	},

	/**
	 * Zdjęcie focusa z pustego pola powoduje przywrócenie informacji
	 */
	_lokalizacjaBlur: function(prefix)
	{
		var input = this._elements[prefix]['lokalizacja'];

		var _this = this;
		if (!input.hasClassName('s4_input_hint') && $F(input) == '') {
			// Scriptaculos działa asynchronicznie
			setTimeout(function() {
				if ($F(input) == '') {
					input.addClassName('s4_input_hint');
					input.setValue(_this._hintText);
				}
			}, 350);
		}
	},

	/**
	 * Metoda odpalana przy wysyłaniu formularza
	 */
	_formSubmit: function(prefix)
	{
		var input = this._elements[prefix]['lokalizacja'];
		
		if (input.hasClassName('s4_input_hint')) {
			input.disable();
//			input.setValue('');
		} else {
			this._miejscowosc[prefix] = [];
			this._dzielnica[prefix] = [];
			this._region[prefix] = '';
			this._setLokalizacjaWiecej(prefix);
		}

		// blokada elementów bez faktycznej wartości na czas szukania
		this._elements[prefix]['form'].select('.hint').invoke('disable');

		// przepisanie kryteriów do elementów
		this._elements[prefix]['region'].setValue(this._region[prefix]);
		this._elements[prefix]['miejscowosc'].setValue(this._miejscowosc[prefix].join('.'));
		this._elements[prefix]['dzielnica'].setValue(this._dzielnica[prefix].join('.'));
	},

	/**
	 * Callback odpalany przez autocompleter, dokleja kryteria
	 */
	callback: function(element, entry)
	{
		// Jesteśmy poza obiektem.
		var prefix = (new RegExp('^s4_([a-z]+)_')).exec(element.id)[1];
		return entry + '&typ=' + encodeURIComponent($F('s4_' + prefix + '_typ')) + '&rynek=' + encodeURIComponent($F('s4_' + prefix + '_rynek')) + '&cel=' + encodeURIComponent($F('s4_' + prefix + '_cel')) + '&przetarg=' + encodeURIComponent($F('s4_' + prefix + '_przetarg'));
	},

	/**
	 * Metoda odpalana przez autocompletera, wyświetla diva z podpowiedziami
	 */
	onShow: function(element, update)
	{
		if (!update.style.position || update.style.position == 'absolute') {
			update.style.position = 'absolute';
			Position.clone(element, update, {
				setHeight: false,
				setWidth: false,
				offsetTop: element.offsetHeight
			});
		}
		update.show();
//		Effect.Appear(update, { duration:0.15 });
	},

	/**
	 * Metoda odpalana przez autocompletera, ukrywa diva z podpowiedziami
	 */
	onHide: function(element, update)
	{
		update.hide();
	},

	/**
	 * Metoda wyświetla cenę/czynsz w zależności od celu transakcji
	 */
	_toggleCenaCzynsz: function(prefix)
	{
		[ 'cena', 'czynsz' ].each(function(el) {
			[ 'element', 'label' ].each(function(id) {
				if (Object.isElement(this._elements[prefix][el + '_' + id])) {
					Common.setDisplay(this._elements[prefix][el + '_' + id], this._elements[prefix]['cel'].getValue() == ((el == 'cena') ? 'sprzedaz' : 'wynajem'));
				}
			}, this);
		}, this);
	},

	/**
	 * Metoda pobiera potrzebne parametry z danej szukarki
	 */
	_getParams: function(prefix)
	{
		var params = {};
		params['typ'] = $F(this._elements[prefix]['typ']);
		params['rynek'] = $F(this._elements[prefix]['rynek']);
		params['cel'] = $F(this._elements[prefix]['cel']);
		params['przetarg'] = $F(this._elements[prefix]['przetarg']);

		return params;
	},

	/**
	 * Metoda ukrywa box regiony/miejscowości
	 */
	hideBoxLokalizacja: function()
	{
		this._elements['box_lokalizacja'].hide();
		this._elements['box_lokalizacja_iframe'].hide();
	},

	/**
	 * Metoda ujawnia box regiony/miejscowości
	 */
	showBoxLokalizacja: function()
	{
		this._elements['box_lokalizacja'].show();
		this._elements['box_lokalizacja_iframe'].show();
		Common.Position.center(this._elements['box_lokalizacja'], {update: true});
		Common.Position.center(this._elements['box_lokalizacja_iframe'], {update: true});
	},

	/**
	 * Metoda wyświetla box z regionami
	 */
	showRegiony: function(prefix)
	{
		this._region[prefix] = '';
		
		var container = this._elements['box_lokalizacja'];
		var indicator = 
			container.visible() ? 
			$('s4_box_lokalizacja_indicator') :
			this._elements[prefix]['indicator'];
		indicator.show();
		
		var _this = this;
		var ajaxObj = new Ajax.Request('/search4,ajax-regiony',
		{
			method: 'post',
			parameters: Object.extend({prefix: prefix}, _this._getParams(prefix, true)),
			onSuccess: function(transport) {
				var response = transport.responseText;
				container.update(response);
				_this.showBoxLokalizacja();
				indicator.hide();
			},
			onFailure: function() { 
				alert(Lang.generic_error);
				indicator.hide();
			}
		});
	},

	/**
	 * Metoda wyświetla box z regionami
	 */
	showMiejscowosci: function(prefix, region)
	{
		if (typeof region == 'undefined') {
			region = this._region[prefix];
			if (region == '') {
				region = $F(this._elements[prefix]['region']);
				this._region[prefix] = region;
			}
		}

		// regulator liczby wierszy miejscowości do iframów
		rows = Object.isElement($('s4_box_miejscowosci_rows')) ? $F('s4_box_miejscowosci_rows') : '';
		
		var container = this._elements['box_lokalizacja'];
		var indicator = 
			container.visible() ? 
			$('s4_box_lokalizacja_indicator') :
			this._elements[prefix]['indicator'];
		indicator.show();
		
		var _this = this;
		var ajaxObj = new Ajax.Request('/search4,ajax-miejscowosci',
		{
			method: 'post',
			parameters: Object.extend({prefix: prefix, region: region, rows: rows}, _this._getParams(prefix, true)),
			onSuccess: function(transport) {
				var response = transport.responseText;
				container.update(response);
				_this.showBoxLokalizacja();
				indicator.hide();

				if (_this._miejscowosc[prefix].length > 0) {
					$$('.s4_miejscowosci_lista input.miejscowosc').each(function(element) {
						if (_this._miejscowosc[prefix].indexOf(element.readAttribute('value')) != -1) {
							element.checked = true;
						}
					});
				}

				if (_this._dzielnica[prefix].length > 0) {
					$$('.s4_miejscowosci_lista input.dzielnica').each(function(element) {
						if (_this._dzielnica[prefix].indexOf(element.readAttribute('value')) != -1) {
							element.checked = true;
						}
					});
				}

			},
			onFailure: function() { 
				alert(Lang.generic_error);
				indicator.hide();
			}
		});
	},

	checkMiejscowosci: function()
	{
		this.uncheckMiejscowosci();
		$$('.s4_miejscowosci_lista input.miejscowosc').each(function(element) { element.checked = true; });
	},

	uncheckMiejscowosci: function()
	{
		$$('.s4_miejscowosci_lista input').each(function(element) { element.checked = false; });
	},

	saveMiejscowosci: function(prefix, region)
	{
		this._miejscowosc[prefix] = [];
		this._dzielnica[prefix] = [];
		this._region[prefix] = region;

		var uncheckedExists = false;
		$$('.s4_miejscowosci_lista input').each(function(element) {
			if (element.checked) {
				if (element.hasClassName('miejscowosc')) {
					this._miejscowosc[prefix].push($F(element));
				} else {
					this._dzielnica[prefix].push($F(element));
				}
			} else if (element.hasClassName('miejscowosc')) {
				uncheckedExists = true;
			}
		}, this);

		if (!uncheckedExists) {
			this._miejscowosc[prefix] = [];
			this._dzielnica[prefix] = [];
		}

		this._setLokalizacjaWiecej(prefix);
		this.hideBoxLokalizacja();

		// wyczyszczenie pola autocompletera
		this._elements[prefix]['lokalizacja'].setValue('');
		this._elements[prefix]['lokalizacja'].removeClassName('s4_input_hint');
		this._lokalizacjaBlur(prefix);
	},

	highlightRegion: function(id)
	{
		element = $('s4_regiony_mapa_region');
		element.src = element.src.replace(/[0-9]+\.gif/, id + ".gif");

		if (typeof this._highlightRegionLastLink != "undefined")
			this._highlightRegionLastLink.removeClassName('highlight');
		
		if (id > 0) {
			link = $('s4_regiony_link_' + id);
			link.addClassName('highlight');
			this._highlightRegionLastLink = link;
		}

	},

	/**
	 * Metoda ustawia odpowiedni link do boxa
	 */
	_setLokalizacjaWiecej: function(prefix)
	{

		if (this._miejscowosc[prefix].length < 1 && this._dzielnica[prefix].length < 1 && this._region[prefix] == '') {
			this._elements[prefix]['wybrane'].hide();
			this._elements[prefix]['wiecej'].show();
		} else {
			var count = this._miejscowosc[prefix].length + this._dzielnica[prefix].length;
			if (count == 0)
				count = 1;
			this._elements[prefix]['wybrane_liczba'].update(count);
			this._elements[prefix]['wiecej'].hide();
			this._elements[prefix]['wybrane'].show();
		}
	},

	_resetLokalizacjaWiecej: function(prefix)
	{
		this._miejscowosc[prefix] = [];
		this._dzielnica[prefix] = [];
		this._region[prefix] = '';
		this._elements[prefix]['wybrane'].hide();
		this._elements[prefix]['wiecej'].show();
		return;
	},

	resetLokalizacja: function(prefix)
	{
		this._resetLokalizacjaWiecej(prefix);
		this.hideBoxLokalizacja();
	},

	toggleLokalizacjaCheckbox: function(element, toggle)
	{
		if (toggle)
			Common.toggleChecked(element);

		var id = element.readAttribute('miejscowosc_id');
		if (element.hasClassName('miejscowosc') && element.checked) {
			$$('.dzielnica_' + id).each(function(e) { e.checked = false; });
		} else if (element.hasClassName('dzielnica') && element.checked) {
			$$('.miejscowosc_' + id).each(function(e) { e.checked = false; });
		}

	}


});
