if (Object.isUndefined(eRabota)) { var eRabota = { } };
if (Object.isUndefined(eRabota.Controls)) { eRabota.Controls = { } };

/**
 * Скрывалка назойливого флеша
 */

function hideFlash() {
	if ($('flashMessage')) {
		Effect.Fade('flashMessage');
	}
	/*
	if ($('errorMessage')) {
		Effect.Fade('errorMessage');
	}*/
}
document.observe('click', function() {
	hideFlash();
});

document.observe('dom:loaded', function() {
	
	$$(".error-message").each(function(el) {
		$(el).up(".item").addClassName("error");
	});
	
	/*
	if ($("errorMessage")) {
		Effect.Pulsate($("errorMessage"), { pulses: 4, duration: 1.3 });
	}*/
	
	setTimeout('hideFlash()', 5000);
});

/**
 * Динамическая подсветка ошибок в формах
 */
Event.observe(document, 'dom:loaded', function() {
	$$(".error-message").each(function(el) {
		$(el).up(".item").addClassName("error");
	});
});

/**
 * Кастомизированный селект
 */
eRabota.Controls.Select = Class.create({
	
	initialize: function(select) {
		var e = Prototype.emptyFunction;
		this.config = Object.extend({
			afterCreate: e,
			beforeDropDown: e,
			afterSelect: e,
			label: 'Select',
			classNames: {
				selector: 'eRabotaSelector',
				dropdown: 'eRabotaSelect',
				arrow: 'i-arrow-down',
				closer: 'closer',
				selected: 'selected'
			},
			showArrow: true
		}, arguments[1] || { });
		
	    this.select = $(select);
		this.active = false;
		
		this.build();
		this.initMouseEvents();
		this.config.afterCreate.call(this);
	},
	
	build: function() {
		
		if (this.select.up().hasClassName('__eRabotaSelect')) {
			this.wrapper = this.select.up();
			this.selector = this.select.next('label'); 
		} else {		
			this.wrapper = this.select.wrap(new Element('span', { 'class': '__eRabotaSelect' }));
			this.selector = new Element('label', { 'class': this.config.classNames.selector }).update(new Element('span').update(this.config.label));
			if (this.config.showArrow) {
				this.arrow = new Element('span', { 'class': 'icon ' + this.config.classNames.arrow }).update(new Element('img', {'src': '/img/pix.gif'}));
				this.selector.insert(this.arrow);
			}
			this.wrapper.insert(this.selector);		
		}
		
		this.dropdown = new Element('div', { 'class': this.config.classNames.dropdown, 'style': 'display: none;' });
		this.closer = new Element('span', { 'class': 'icon i-closer ' + this.config.classNames.closer, 'title': 'Закрыть' }).update(new Element('img', { 'src': '/img/pix.gif' }));
		this.list = new Element('ul');
		
		$A(this.select.options).each(function(option, i) {
			var item = new Element('li').update(option.text);
			//item.writeAttribute('value', i);
			this.list.insert(item);
		}.bind(this));
		
		this.dropdown.insert(this.list);
		this.dropdown.insert(this.closer);
		
		document.body.appendChild(this.dropdown);
		
		this.select.hide();
		
		this.set(this.select.selectedIndex);
		
		this.select.hideAndDisable = this.hideAndDisable.bind(this);
		this.select.showAndEnable = this.showAndEnable.bind(this);
		
		if (this.select.disabled) {
			this.hideAndDisable();
		}
		
 		//new eRabota.Effects.Shadow(this.dropdown);
 	},
	
	initMouseEvents: function() {
		this.select.observe('change', this.onSelectChanged.bind(this));
		this.select.observe('eRabotaSelect:change', this.onSelectChanged.bind(this));
		this.selector.observe('click', this.onDropDown.bind(this));
		Event.observe(document, 'click', this.onDocumentClick.bind(this));
		new eRabota.Controls.RadioList(this.list, { onChange: this.onSelect.bind(this) });
		
		if (this.closer) {
			this.closer.observe('click', this.hide.bind(this));
		}
	},
	
	onDocumentClick: function(event) {
		if (!this.active || Event.element(event).up('.__eRabotaSelect') == this.select.up()) return;
		this.hide();
	},
	
	onDropDown: function() {
		this.config.beforeDropDown.call(this);
		(this.active) ? this.hide() : this.show();
	},
	
	onSelect: function(selected) {
		this.list.select('li').each(function(option, i) {
			if (option == selected) {
				this.set(i);
				this.config.afterSelect.call(this);
			}
		}.bind(this));	
	},
	
	onSelectChanged: function() {
		this.set(this.select.selectedIndex);
		this.config.afterSelect.call(this);
	},
	
	show: function() {
		this.move();
		this.active = true;
		this.dropdown.appear({ duration: 0.2 });
	},
	
	hide: function() {
		this.active = false;
		this.dropdown.fade({ duration: 0.2 });
	},
	
	move: function() {
		position = this.wrapper.cumulativeOffset();
		this.dropdown.setStyle({
			'left': position.left + 'px',
			'top': position.top + 'px'
		});
	},
	
	set: function(index) {
		this.selector.down('span').update(this.select.options[index].text);
		this.select.selectedIndex = index;
		// TODO переложить переключение классов на eRabota.Controls.RadioList
		this.list.select('li').invoke('removeClassName', this.config.classNames.selected);
		this.list.down('li', index).addClassName(this.config.classNames.selected)
		this.hide();
	},

	setValue: function(value) {
		$A(this.select.options).each(function(option, i) {
			if (value == option.value) {
				this.set(i);
				return;
			}
		}.bind(this));	
	},
	
	getValue: function() {
		return this.select.options[this.select.selectedIndex].value;
	},
	
	hideSelect: function() {
		this.selector.hide();
		this.hide();
	},
	
	showSelect: function() {
		this.selector.show();
	},
	
	hideAndDisable: function() {
		this.select.disable();
		this.hideSelect();
	},

	showAndEnable: function() {
		this.select.enable();
		this.showSelect();
	}
	
});

/**
 * Всплывающий слой
 */
eRabota.Controls.Popup = Class.create({
	
	initialize: function(popup) {
		var e = Prototype.emptyFunction;
		this.config = Object.extend({
			afterLoad: e
		}, arguments[1] || { });

	    this.popup = $(popup);
		this.active = false;
		this.opener = null; 
		
		this.container = new Element('div', {
			'className': 'eRabotaPopupContainer',
			'style': 'position: absolute; z-index:100; display:none;'
		});
		document.body.appendChild(this.container);
		this.container.update(this.popup.remove());
		
		this.popup.show();
		
		this.initMouseEvents();
	},
	
	initMouseEvents: function() {
		Event.observe(document, 'click', this.onDocumentClick.bind(this));
		
		this.container.select('.closer, .cancel').each(function(item) {
			$(item).observe('click', function(e) {
				this.hide();
				Event.stop(e);
			}.bind(this));
		}.bind(this));
	},
	
	onDocumentClick: function(event) {
		if (!this.active) return;
		var el = Event.element(event);
		if (this.opener && (el == this.opener || el.up() == this.opener)) return;
		if (el == this.container || el.up('.eRabotaPopupContainer') == this.container) return;
		this.hide();
	},
	
	show: function(position) {
		if (Object.isElement(position)) {
			this.opener = position; 
		}
		if (position) {
			this.opener = position; 
			this.move(position);			
		}
		this.active = true;
		this.container.appear({ duration: 0.2 });
	},
	
	hide: function() {
		this.active = false;
		this.container.fade({ duration: 0.2 });
	},

	move: function(position) {
		if (Object.isArray(position)) {
			position = { left: position[0], top: position[1] };
		} else if (Object.isElement(position) || Object.isString(position)) {
			position = $(position).cumulativeOffset();
		}
		
		var w = (document.body.scrollWidth > document.body.offsetWidth)?document.body.scrollWidth:document.body.offsetWidth;
		var h = (document.body.scrollHeight > document.body.offsetHeight)?document.body.scrollHeight:document.body.offsetHeight;
		var offset = 20;
		
		if ((position.left + this.container.getWidth()) > (w - offset)) {
			position.left -= (position.left + this.container.getWidth()) - (w - offset); 
		}
		if ((position.top + this.container.getHeight()) > (h - offset)) {
			position.top -= (position.top + this.container.getHeight()) - (h - offset); 
		}
		
		this.container.setStyle({
			'left': position.left + 'px',
			'top': position.top + 'px'
		});
	}
});

/**
 * Всплывающий слой с загрузкой контента
 */
eRabota.Controls.AjaxPopup = Class.create(eRabota.Controls.Popup, {
	
	initialize: function(url) {
		var e = Prototype.emptyFunction;
		this.config = Object.extend({
			method: "get",
			parameters: { },
			afterLoad: e
		}, arguments[1] || { });
		
		this.url = url;
		this.container = null;
		this.active = false;
		this.opener = null;
		this.loading = false;
	},
	
	load: function(position, bShow) {
		if (this.loading) return;
		this.loading = true;
		new Ajax.Request(this.url, {
			method: this.config.method || "get", 
			parameters: this.config.parameters || { },
			onSuccess: function(response) {
				this.build(response.responseText);
				this.initMouseEvents();
				this.config.afterLoad.call(this);
			 	if (bShow) this.show(position);
			 	this.loading = false;
			 }.bind(this)
		});
	},
	
	build: function(content) {
		this.container = new Element('div', {
			'className': 'eRabotaPopupContainer',
			'style': 'position: absolute; z-index:100; display:none;'
		});
		this.container.update(content);
		document.body.appendChild(this.container);
		//new eRabota.Effects.Shadow(this.container);
		
		//this.closer = this.container.down('.closer');
	},
	
	show: function(position) {
		if (Object.isElement(position)) {
			this.opener = position; 
		}
		if (!this.container) {
			this.load(position, true);
			return;
		}
		if (position) {
			this.move(position);
		}
		this.active = true;
		this.container.appear({ duration: 0.2 });
	}
});

/**
 * Разворачиватель чего-либо.
 */
eRabota.Controls.Expander = Class.create({
	
	initialize: function(link, div, options) {
		this.link = $(link);
		this.div = $(div);
		this.options = options || {};
		this.options.expandLabel = this.options.expandLabel || 'Развернуть';
		this.options.collapseLabel = this.options.collapseLabel || 'Свернуть';
		
		this.options.onCollapse = this.options.onCollapse || Prototype.emptyFunction;
		this.options.onExpand = this.options.onExpand || Prototype.emptyFunction;
		
		this.link.observe('click', this.handleClick.bind(this));
		
		this[this.options.bExpand ? 'expand' : 'collapse']();
	},
	
	handleClick: function(event) {
		this[this.div.hasClassName('collapsed') ? 'expand' : 'collapse']();
		this.link.blur();
		Event.stop(event);
		return false;
	},
	
	collapse: function() {
		this.link.update(this.options.expandLabel);
		this.div.addClassName('collapsed');
		this.options.onCollapse.call(this);
	},
	
	expand: function() {
		this.link.update(this.options.collapseLabel);
		this.div.removeClassName('collapsed');
		this.options.onExpand.call(this);
	}
});

/**
 * Добавляет в инпуты примера значения
 */
eRabota.Controls.PlaceHolder = Class.create({
	
	initialize: function(element, msg, restore) {
		this.element = $(element);
		this.msg = msg;
		this.restore = restore || false;
		
		this.element.observe('focus', this.clearMsg.bind(this));

		if (this.element.form) {
			$(this.element.form).observe('submit', this.clearMsg.bind(this));
		}

		if (this.restore) {
			this.element.observe('blur', this.setMsg.bind(this));
		}

		this.setMsg();
	},
	
	setMsg: function() {
		if (!this.element.value || this.element.value == this.msg) {
			this.element.addClassName('placeholder');
			this.element.value = this.msg;
		} else {
			this.element.removeClassName('placeholder');
		}
	},
	
	clearMsg: function() {
		this.element.value = (this.element.value == this.msg) ? '' : this.element.value;
		this.element.removeClassName('placeholder');
	}
});


/**
 * Менеджер формы поиска по сайту
 */

eRabota.Controls.SiteSearchManager = Class.create({
	initialize: function(form, select, input) {
		this.form = $(form);
		this.input = $(input);
		
		this.select = new eRabota.Controls.Select($(select), {
			'afterSelect': function() {
				this.setSearch();
				this.input.focus();
			}.bind(this)
		});
		var action = Cookie.get('site-search-type') || null;
		if (action) { this.setSearch(action); }
		
		new eRabota.Controls.PlaceHolder(this.input, 'Введите ключевые слова для поиска...', true);
	},
	
	setSearch: function(action) {
		if (!action) {
			action = this.select.getValue();
		} else {
			this.select.setValue(action);
		}
		this.form.action = action;
		Cookie.set('site-search-type', action, 365);
	}
});


/**
 * Менеджер блоков формы
 */
eRabota.Controls.FormBlockManager = Class.create({
	
	initialize: function(container, blockType) {
		this.BlockType = blockType || eRabota.Controls.FormBlock;
		this.container = $(container);
		this.init();
	},
	
	init: function() {
		this.createList();
		this.createSortable();
		this.format();
	},
	
	createList: function() {
		this.blocks = new Array();
		
		this.container.select('.form-block').each(function(block, i) {
			this.blocks[i] = new this.BlockType(this, block, i);
		}.bind(this));
	},
	
	createSortable: function() {
		if (this.blocks.size() > 1) {
			Sortable.create(this.container, {
				tag: 'div',
				scroll: window,
				onChange: function() {
					this.format();
				}.bind(this)
			});
		} else {
			Sortable.destroy(this.container);
		}
	},
	
	format: function() {
		this.container.select('.form-block').each(function(block, i) {
			block.down('h2')[i == 0 ? 'show' : 'hide']();
			block.down('.form-block-add')[i < this.blocks.size() - 1 ? 'hide' : 'show']();
		}.bind(this));
	},
	
	add: function() {
		var clone = this.blocks[0].clone();
		this.container.insert(clone.getElement());
		this.blocks[this.blocks.size()] = clone;
		this.createSortable();
		this.format();
		
		if (clone.block.down("._company")) {
			new eRabota.Controls.CompanyAutocomplete(clone.block.down("._company"));
		}
		
		return false;
	},
	
	remove: function(block) {
		block.getElement().remove();
		this.blocks = this.blocks.without(block);
		this.createSortable();
		this.format();
	}
});

eRabota.Controls.FormBlock = Class.create({
	
	initialize: function(manager, block, i) {
		this.manager = manager;
		this.block = $(block);
		
		if (this.getElement().down('.add-link')) {
			this.getElement().down('.add-link').observe("click", this.manager.add.bind(this.manager));
		}
		if (this.getElement().down('.remove-link')) {
			this.getElement().down('.remove-link').observe("click", this.remove.bind(this));
		}
		
		this.init();
	},
	
	init: function() {
	},
	
	getElement: function() {
		return this.block;
	},
	
	clear: function() {
		this.getElement().select('input').each(function(_field) {
			_field.clear();
		});
		this.getElement().select('select').each(function(_field) {
			_field.selectedIndex = 0;
		});
		this.getElement().select('textarea').each(function(_field) {
			_field.clear();
		});
	},
	
	remove: function() {
		if (this.manager.blocks.size() > 1) {
			this.manager.remove(this);
		} else {
			return this.clear();
		}
		
		return false;
	},
	
	clone: function() {
		var new_el = new Element('div', { 'className': 'form-block relative' } );
		var _html = this.getElement().innerHTML;
		
		// Replace 'name' attriutes
		_html = _html.gsub(/\[(\d+)\]/, function(match) {
			return '[' + this.manager.nextIndex + ']';
		}.bind(this));
		
		// Replace 'id' attriutes
		_html = _html.gsub(/([\"\'])([A-Za-z]+)(\d+)([A-Za-z]+)\1/, function(match) {
			return match[2] + this.manager.nextIndex + match[4];
		}.bind(this));
		
		this.manager.nextIndex++;
		
		var block = new this.manager.BlockType(this.manager, new_el.update(_html));
		block.clear();
		
		return block;
	}
});

/**
 * Блок формы обучения (наследуется от FormBlock)
 */
eRabota.Controls.EducationBlock = Class.create(eRabota.Controls.FormBlock, {
	init: function($super) {
		$super();
		
		this.edu_level = this.getElement().select('select')[0];
		this.edu_type = this.getElement().select('select')[1];
		
		this.updateType();
		
		this.edu_level.observe("change", function(e) {
			this.updateType();
		}.bind(this));
	},
	
	// TODO: Временное решение, придумать лучше
	updateType: function() {
		switch (this.edu_level.value ) {
			case 'unfinished':
			case 'bachelor':
			case 'specialist':
			case 'master':
			case 'candidate':
			case 'doctorate':
				this.edu_type.enable();
				break;
			default:
				this.edu_type.selectedIndex = 0;
				this.edu_type.disable();
				break;
		}
	},
	
	clear: function($super) {
		$super();
		
		this.getElement().down('._period_from').down('input[type=hidden]').value = '01';
		this.getElement().down('._period_to').down('input[type=hidden]').value = '01';
	}
});

/**
 * Блок формы опыта работы (наследуется от FormBlock)
 */
eRabota.Controls.WorkExperienceBlock = Class.create(eRabota.Controls.FormBlock, {
	init: function($super) {
		$super();
		new eRabota.Controls.CompanyAutocomplete(this.block.down("._company"));
	},
	
	clear: function($super) {
		$super();
		
		var expType = this.getElement().down('input[type=radio]');
		if (!Object.isUndefined(expType)) {
			expType.checked = (expType.value == 'permanent') ? 1 : 0;
		}
		
		this.getElement().down('._period_from').down('input[type=checkbox]').checked = true;
		this.getElement().down('._period_from').down('input[type=hidden]').value = '01';
		this.getElement().down('._period_to').down('input[type=hidden]').value = '01';
		this.getElement().down('._period_to').hide();
	}
});

eRabota.Controls.CompanyAutocomplete = Class.create({
	initialize: function(element) {
		var input = element.down("input");
		var indicator = element.down(".preloader-indicator");
		var auto_complete = element.down(".auto_complete");
		input.setAttribute("autocomplete", "off");
		new Ajax.Autocompleter(
			input,
			auto_complete,
			"/my/company/search",
			{
				indicator: indicator,
				paramName: "data[Company][title]",
				updateElement: function(item) {
					input.value = $(item).down(".value").innerHTML.strip();
				}
			}
		);
	}
});


/**
 * Менеджер тегов
 */
eRabota.Controls.TagsManager = Class.create({
	initialize: function(ul, input, options, tagClass) {
		
		this.ul = $(ul);
		this.input = $(input);
		
		this.options = options || {};
		this.field = this.options.field || 'tags';
		this.source = this.options.source || [];
		this.tagClass = tagClass || eRabota.Controls.Tag;
		this.tags = [];
		
		this.init();
	},
	
	init: function() {
		
		this.autocomplete = new Element('div', { 'class': 'autocomplete' } );
		this.input.up().insert(this.autocomplete);
		
		if (typeof(this.source) == "object") {
			new Autocompleter.Local(this.input, this.autocomplete, this.source, { ignoreCase: true, afterUpdateElement: this.onSelect.bind(this) } );
		} else {
			new Ajax.Autocompleter(this.input, this.autocomplete, this.source, { paramName: this.field, ignoreCase: true, afterUpdateElement: this.onSelect.bind(this) } );
		}
		this.input.observe('keypress', this.onKey.bindAsEventListener(this));
		this.input.observe('blur', this.onBlur.bindAsEventListener(this));
		
		this.add();
		
		if (typeof(this.options.values) == "object") {
			this.options.values.each(function(value) {
				this.add(value);
			}.bind(this));
		}
	},
	
	onKey: function(e) {
		if (e.keyCode == Event.KEY_RETURN) {
			Event.stop(e);
			this.add();
		} else {
			values = this.extract(this.input.value);
			if (values.length > 1) {
				values.pop();
				this.add(values);
			}
		}
	},
	
	onSelect: function(input, element) {
		this.add(input.value);
	},
	
	onBlur: function() {
		if (!this.input.value) return;		
		this.add(this.input.value);
	},
	
	add: function(values, options) {
		var values = values || this.input.value;
		this.input.value = '';
		
		if (!values) return;
		
		if (typeof(values) == 'string') {
			values = this.extract(values);
		}
		
		values.each(function(value) {
			value = value.trim();
			if (value && !this.find(value)) {
				var tag = new this.tagClass(this, value, options);
				this.tags.push(tag);
				this.ul.insert(tag.getElement());
			}
		}.bind(this));
	},
	
	extract: function(str) {
		return str.split(',').invoke('trim');
	},
	
	find: function(value) {
		var ret = null; 
		this.tags.each(function(tag) {
			if (tag.getValue().toLowerCase() == value.toLowerCase()) {
				ret = tag;
				return;
			}
		});
		return ret;
	},
	
	remove: function(item) {
		this.tags = this.tags.without(item);
	}
});

/**
 * Блок тега
 */
eRabota.Controls.Tag = Class.create({
	initialize: function(manager, value, options) {
		this.manager = manager;
		this.value = value;
		this.options = options || {};
		
		this.element = this.createElement(this.value);
		
		this.element.down('.icon').observe('click', this.remove.bind(this));		
	},
	
	createElement: function(value) {
		var element = new Element('li');
		element.insert(new Element('input', { 'type': 'hidden', 'name': this.manager.options.field + '[]', 'value': value } ));
		element.insert(new Element('span', { 'class': 'icon i-closer', 'title': 'Удалить' } ).update(new Element('img', {'src': '/img/pix.gif'})));
		
		var url = this.manager.options.url || '';
		if (url) {		
			element.insert(
					new Element('span', { 'class': 'value' } ).update(
						new Element('a', { 'href': url + value }).update(value)
					)
				);
		} else {
			element.insert(new Element('span', { 'class': 'value' } ).update(value));
		}
		
		return element;
	},
	
	getValue: function() {
		return this.value;
	},
	
	getElement: function() {
		return this.element;
	},
	
	remove: function() {
		this.getElement().remove();
		this.manager.remove(this);
	}
});

/**
 * Блок языкового тега
 */
eRabota.Controls.LanguageTag = Class.create(eRabota.Controls.Tag, {
	createElement: function ($super, value) {
		
		var element = new Element('li');
		element.insert(new Element('span', { 'class': 'icon i-closer', 'title': 'Удалить' } ).update(new Element('img', {'src': '/img/pix.gif'})));
		element.insert(new Element('span', { 'class': 'value' } ).update(value));
		
		var levels = this.manager.options.levels || {};
		if (!levels) return element;
		
		this.select = new Element('select', { 'name': this.manager.options.field + '[' + this.getValue() + ']'});
		
		levels.each(function(pair) {
			var option = new Element('option', { 'value': pair.key } ).update(pair.value);
			this.select.insert(option);
		}.bind(this));
		
		element.insert(this.select);
		this.levels = new eRabota.Controls.Select(this.select);
		
		var level = this.options.level || this.manager.options.level;
		
		if (level) {
			this.levels.setValue(level);
		}
		
		return element;
	}
});

/**
 * Переключалка режимов сортировки на основе радиосписка
 */
eRabota.Controls.Sorter = Class.create({
	initialize: function(menu, url) {
		this.url = url;
		this.menu = $(menu);
		this.radioList = new RadioList(this.menu, {
			onChange: this.updateOrder.bind(this)
		});
	},
	
	updateOrder: function(selectedItem) {
		order = selectedItem.getAttribute("value");
		link = selectedItem.down("a");
		direction = link.hasClassName("asc") ? "desc" : "asc";
		
		this.menu.select("a").each(function (el) {
			el.removeClassName("asc").removeClassName("desc");
		});
		link.addClassName(direction);
		
		requestParameters = window.location.search.toQueryParams();
		requestParameters.order = order;
		requestParameters.dir = direction;
		new Ajax.Updater("main_content", this.url, {
			method: "get",
			parameters: requestParameters,
			onCreate: Element.show.curry("preloader-indicator"),
			onComplete: Element.hide.curry("preloader-indicator")
		});
	}	
});

/**
 * Открывалка-закрывалка форм, встроенных в сообщения (form-content внутри message-box)
 */
eRabota.Controls.ReplyForm = Class.create({
	initialize: function(message) {
		this.message = $(message);
		this.replyLink = this.message.down('.reply');
		if (!this.replyLink) return;
		this.form = this.message.down('.form-content');
		if (!this.form) return;
		this.cancelLink = this.form.down('.cancel');
		
		if (this.replyLink) {
			this.replyLink.observe('click', function(e) {
				Event.stop(e);
				this.replyLink.up('.actions').hide();
				this.message.addClassName('m-form');
			}.bind(this));
		}
		if (this.cancelLink) {
			this.cancelLink.observe('click', function(e) {
				Event.stop(e);
				this.replyLink.up('.actions').show();
				this.message.removeClassName('m-form');
			}.bind(this));
		}
	}
});



