js={};js.loadedModules={};js.rootUrl='/js/';js.include=function(list){if(typeof list=='string'){list=[list];}
var include=[];for(var i=0,ci=list.length;i<ci;i++){if(!js.loadedModules[list[i]])include.push(list[i]);}
if(include.length==0)return;js.load(include);}
js.load=function(list){var transport=js.getXHTTPTransport();var url=js.rootUrl;for(var i=0,ci=list.length;i<ci;i++){url+=list[i]+'.js'+(i==ci-1?'':',');}
transport.open('GET',url,false);transport.send(null);var code=transport.responseText;eval(code);}
js.getXHTTPTransport=function(){var result=false;var actions=[function(){return new XMLHttpRequest()},function(){return new ActiveXObject('Msxml2.XMLHTTP')},function(){return new ActiveXObject('Microsoft.XMLHTTP')}];for(var i=0;i<actions.length;i++){try{result=actions[i]();break;}catch(e){}}
return result;}
js.module=function(path){js.loadedModules[path]=true;};/**
 * Базовый JS, в котором определены основные функции и объекты,
 *  а также производится инициализация объектов/переменных общих для все страниц
 */

js.module('main');
js.include('ajax');
// Переменная, показывающая скрывать по клику всплывающие слои или нет.
var outDiv = 0;
var home=0;
var requestUri = '/data/';
var clearInt = 0;
var PhoneBlockList = [];
var validator = '';
var mapsUrl = 'http://' + env_prefix + 'maps.ngs.ru' + env + '/dictionary';
var SearchAutocomplete = null;

$(document).ready(function() {

	var objectSearch = $('#object-search');
	if (objectSearch.length && objectSearch.attr('autocomplete') == 'off') {
		SearchAutocomplete = $('#object-search').autocomplete({
			serviceUrl : '/suggest/' + (objectSearch.hasClass('search-resume') ? 'resume' : 'vacancy'),
			noCache : true,
			queryType : 'json',
			deferRequestBy: 100,
			maxHeight: 600
		});
	}

	if(navigator.userAgent.indexOf("Macintosh")!=-1) {
		$('#content div.form-search-block table.form-search-table td.butt-search input.button, #content div.form-search-block table.form-search-table td.where-search select').css('font-size', '17px !important');
	}

	var buttons = $(".sprited-button"),
		buttons2 = $(".button-green"),
		dropdowns = $(".dd-container"),

		links_list = $("#top-toolbar td.cp-links ul.links.cp"),
		username = links_list.children(".username"),
		username_wrapper_width = username.children(".username-wrapper").outerWidth(true),
		links_list_width = username_wrapper_width,
		white_gradient = $("ul.links.cp span.white-gradient");

	links_list.children().not(".username").each(function() {
		links_list_width += $(this).outerWidth(true);
	});

	links_list.css({ maxWidth: links_list_width + "px" });

	$(window).resize(function() {
		(typeof smooth_out_cp_links != "undefined") && smooth_out_cp_links();
	});

	$(window).resize();

	// Popup for messages
	$('.popWindowJs, .request-img, .request-link, .reply-popup').popupWindow({ 
		centerScreen:1,
		width: 800,
		height: 660,
		scrollbars: 'yes'
	});

	$(window).resize();

	Items.init();

	// Events handling
	$('#quick-select a').click(function() {
		return quickSelect(this);
	});

	// Sprited buttons
	set_buttons_behavior(buttons2);
	set_buttons_behavior(buttons);


	// Elements which contains radio buttons
	$(".used-as-radio:not(.with-dropdown)").click(function() {
		$(".ab-radio, .radio", this).attr("checked", "checked")
			.filter(".enables-text-input").change();
	});

	// Dropdown controller
	$(".with-dropdown").click(function() {
		var dropdown_handler = $(this).parents(".dd-handler"),
				dropdown_container = dropdown_handler.next();

		dropdown_container.toggle();
		dropdowns.not(dropdown_container).hide();
	});

	dropdowns
		.mouseout(function() {
			$("body").data("can_close_popups", true);
		})

		.mouseover(function() {
			$("body").data("can_close_popups", false);
		})

		.find(".used-as-radio")

			// Клик по радиокнопке в выпадашке
			.click(function() {
				$(this)
					.parents(".dd-container").prev()
						.find(".ab-radio").attr("checked", "checked");
			}).end()

		.find(".hides-dropdown-on-return")

			.keydown(function(event) {
				var keycode = event.which;

				if (keycode == "13") { // Enter
					$(this).parents(".dd-container").hide();

					return false;
				}
			});

	$(".hides-dropdown").click(function() {
		dropdowns.hide();
		/*@cc_on
		$(".hidden-by-popup").show();
		@*/
	});



	$(".controls-text-input").change(function() {

		var controller = $(this),
				controller_id = parseInt($(this).attr("id").match(/\d+$/));

		$(".enabled-by-radio").each(function() {
			var text_input_id = parseInt($(this).attr("id").match(/\d+$/));

			if (text_input_id == controller_id) {
				if (controller.hasClass("enables-text-input")) {
					$(this).removeAttr("disabled").focus();
				}
				else
					if (controller.hasClass("disables-text-input")) {
						$(this).attr("disabled", "disabled");
					}

				return;
			}
		});
	});

	$(".closes-the-popup").click(function() {
		$(this).parents(".popup").hide();
		/*@cc_on
		$(".hidden-by-popup").show();
		@*/
		return false;
	});

	GrayHelp.init();
	KeyControl.init();
	Editable.init();
	Tabs.init();
	Tabs2.init();

	$(document).pngFix();

	$("body").click(function() {
		if ($(this).data("can_close_popups")) {dropdowns.hide(); }
		closeDivBody();
	});

	$("body").keyup(function(event) {
		var keycode = event.which;

		if (keycode == "27") // Esc
			dropdowns.hide();
	});

	/* Pirobox */
	js.include('jquery/pirobox');
	jQuery().piroBox({
		my_speed: 300, //animation speed
		bg_alpha: 0.1, //background opacity
		slideShow : true, // true == slideshow on, false == slideshow off
		slideSpeed : 6, //slideshow duration in seconds(3 to 6 Recommended)
		close_all : '.piro_close,.piro_overlay'// add class .piro_overlay(with comma)if you want overlay click close piroBox
	});

	hideEmptyPlaces();
	hideEmptyPlacesLine(); // Скрываем пустые места в линейке баннеров
});


/**
 * Функция "Добавить в Избранное"
 *
 */
function add2Fav(url,title,link_name) {
	if (!url) url = location.href;
	if (!title) title = document.title;

	if ((typeof window.sidebar == "object") && (typeof window.sidebar.addPanel == "function")) {
		window.sidebar.addPanel (title, url, "");
	} else if (typeof window.external == "object") {
			window.external.AddFavorite(url, title);
	} else if (window.opera && document.createElement) {
	    document.getElementById(link_name).setAttribute('rel','sidebar');
	    document.getElementById(link_name).setAttribute('href',url);
	    document.getElementById(link_name).setAttribute('title',title);
	} else {

		return false;
	}

	return true;
}

/**
 * Функция, показывающая/скрывающия всплывающие слои.
 *
 * @param item_id идентификатор слоя, который нужно скрыть/показать
 */
function displaySelector(item_id) {
	var obj = $("#" + item_id);

	if ($("#" + item_id).css("display") != 'none') {
		obj.hide();
	} 
	else {
		$('.popdivs').hide();
		obj.show();
	}
}

/**
 * Функция, скрывающая все всплывающие слои с классом popdivs
 */
function closeDivBody() {
	if (outDiv == 1) {
		$('.popdivs').hide();

		//if (typeof(clearInt) != 'undefined') {
			clearInterval(clearInt);
		clearInt = 0;
		//}
		/*@cc_on
		$(".hidden-by-popup").show();
		@*/

		if (window.ActiveXObject && window.navigator.userProfile) { // если IE6
			if ($('iframe.hide-sel-frame')) {
				$('iframe.hide-sel-frame').remove(); // удаляем iframe скрывающий select-ы в IE6
			}
		}
	}
}

/**
 * Функция, генерирующая для валидатора слой с текстом, что поле заполнено верно
 *
 * @param elementWidth
 * @param elementHeight
 */
function getOkMessage(elementWidth, elementHeight) {

	var icoErrorLeft = elementWidth + 17;
	var icoErrorBottom = elementHeight - 14;

	return "<div class='ok-ico' style='bottom:"+ icoErrorBottom +"px !important; left:"+ icoErrorLeft +"px !important;'></div>";
}

/**
 * Функция, генерирующая для валидатора слой с текстом, что в поле содержится ошибка
 *
 * @param message
 * @param element
 * @param elementWidth
 * @param elementHeight
 */
function getErrorMessage(message, element, elementWidth, elementHeight) {

	var icoErrorLeft = elementWidth + 17;
	var popErrorLeft = elementWidth - 8;
	var icoErrorBottom = elementHeight - 16;
	var popErrorBottom = elementHeight - 2;

	elementSelector =element.replace(/[\[\]]/g, '\\\\$&');
	return "<div class='error-ico' style='bottom:"+ icoErrorBottom +"px !important; left:"+ icoErrorLeft +"px !important;' onclick='$(\"#error-mess-"+elementSelector+"\").show();'></div>" +
				"<div id='p-error-mess-"+element+"' class='error-mess' style='bottom:"+ popErrorBottom +"px !important; left:"+ popErrorLeft +"px !important;'>" +
					"<div id='error-mess-"+element+"' class='error-mess-"+element+"' style='display:;'>"+
						"<table class='error-shadows'>"+
						"<tr>" +
							"<td class='top-left'></td>"+
							"<td class='top-center'></td>"+
							"<td class='top-right'></td>"+
						"</tr>"+
						"<tr>"+
							"<td class='middle-left'></td>"+
							"<td class='middle-center'>"+
								"<div class='close-div'><div class='close' onclick=\"$('#error-mess-"+elementSelector+"').hide();\"></div></div>"+
								message +
							"</td>"+
							"<td class='middle-right'></td>"+
						"</tr>"+
						"<tr>"+
							"<td class='bottom-left'></td>"+
							"<td class='bottom-center'>"+
							"<div class='corner-div'><div class='bottom-corner'>&nbsp;</div></div>"+
							"<div class='bottom-line'>&nbsp;</div></td>"+
							"<td class='bottom-right'></td>"+
						"</tr>"+
						"</table>"+
					"</div>"+
				"</div>";
}

/**
 * Makes a string's first character uppercase
 *
 * version: 1008.1718
 * discuss at: http://phpjs.org/functions/ucfirst
 * original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
 * +   bugfixed by: Onno Marsman
 * +   improved by: Brett Zamir (http://brett-zamir.me)
 * *     example 1: ucfirst('kevin van zonneveld');
 * *     returns 1: 'Kevin van zonneveld'
 * @param str
 */
var ucfirst = function (str) {
    str += '';
    var f = str.charAt(0).toUpperCase();
    return f + str.substr(1);
}

/**
 * Показывает загрузчик при AJAX-запросе
 */
function ShowLoader() {
	$('#loader').show();
}

/**
 * Скрывает загрузчик после AJAX-запроса
 */
function HideLoader() {
	$('#loader').hide();
}

/**
 * Генерирует ссылку к стораджу для генерации превью изображения
 *
 * @param pathToFile
 * @param width
 * @param height
 */
var makePreviewUrl = function (pathToFile, width, height) {
	var expr = /(\w\w)\.(\w\w)\.(\w\w)\.tmp\.storage\.ngs\.ru(?:\.d|\.t[0-9]?)?\/(\w{26}\.\w+)/;

	var matches = pathToFile.match(expr);

	var newUrl = "/tpic/"+width+"/"+height+"/crop/" + matches.slice(1).join('');

	return newUrl;
};

/**
 * Открывает всплывающее окошко с указанным урлом
 * @param url
 * @param title
 */
var windowOpen = function(url, title) {
	if (title === undefined)
		title = '';
	window.open(
		url + '?title=' + title + '&short_form=1',
		title,
		'location=no,locationbar=no,toolbar=no,directories=no,menubar=no,status=no,scrollbars=yes,width=800,height=480,top=200,left=200'
	);

	return false;
}

/**
 * Функция, выделяющая текст
 * @param obj Объект выделения
 */
var selectText = function(obj) {
	obj.focus().select();
}

/**
 * Класс, управляющий записями в списках
 */
var Items = {
	readList: new Array(),
	item: '#item-', // ID строки в списке
	item2: '#item2-', // ID строки с серой плашкой или подробным описанием в списке
	header: '#h-', // ID заголовка записи
	underline: '#s-', // ID подчеркивающего курсивом span
	cookie: 'readList', // cookie

	init: function() {
		this.markAsRead();
		
		if (!$.cookie(this.cookie)) {
			$.cookie(this.cookie, 1, {expires:3600*24*30, path:'/'});
		}
	},

	// Раскрытие подробного вида и отметка о прочтении
	toggleItem: function(id) {
		
		$(this.item + id + ' .post-short,' + this.item + id + ' .post-full').toggle();
		$(this.item2 + id + ' .post-short,' + this.item2 + id + ' .post-full').toggle();
		this.collectIds(id);
		this.plusOne(id);
		
		return false;
	},

	// Сбор просмотренного
	collectIds: function(id) {
		$(this.header + id).addClass('is-read');
		
		$(this.underline + id)
			.removeClass('dotted')
			.addClass('dotted-read');

		if ($.cookie(this.cookie)) {
			current = $.cookie(this.cookie);
			this.readList = current.split(',');
		}

		if ($.cookie(this.cookie) && $.cookie(this.cookie).indexOf(id) == -1) {
			this.readList.push(id);
			$.cookie(this.cookie, this.readList.join(), {expires:3600*24*30, path:'/'});
		}
	},

	// Пометка просмотренных ссылок
	markAsRead: function() {
		if ($.cookie(this.cookie)) {
			current = $.cookie(this.cookie);
			this.readList = current.split(',');

			for (var id in this.readList) {
				$(this.header + this.readList[id]).addClass('is-read');

				$(this.underline + this.readList[id])
					.removeClass('dotted')
					.addClass('dotted-read');
			}
		}
	},

	plusOne: function() {
		return ajaxCustomRequest('', arguments, 'POST', '/data/plusOne');
	},

	// debug
	dbg: function(value) {
		console.log(value);
	}
}

/*
	 * Функция подсчитывающая минимальную ширину колонки с Должностью
	 * Необходима для исправления бага в IE: 
	 * при раскрывании подробного вида вакансий и резюме в ЛК - 
	 * ширина колонки скачет из-за colspan
	 */
	var colspanTablePosts = function() {
		
			var spacerPost = $('.listItemsJS').find('th.post').find('.spacer');
			
			if ($(window).width() < widthWindowBrows) {
					
				spacerPost.css('width', '');
				
			}
			
			var widthTable = $('.listItemsJS').outerWidth();
			
			var sumTh = 0;
			var sumDinamTh = 0;
			var sumFixThTemp = 0;
			var paddPost = 0;
			
			$('th', '.listItemsJS').each(function() {
				
				if (!($(this).hasClass('post'))) {
					
					if (($(this).css('width') == '0px') || ($(this).css('width') == 'auto')) {
						
						sumDinamTh = sumDinamTh + $(this).outerWidth();
						
					} else {
						/*if (sumFixTh == 0) {
							sumFixTh = sumFixTh + $(this).outerWidth();
						}*/
						
						if (sumFixTh == 0) {
							sumFixThTemp = sumFixThTemp + $(this).outerWidth();
						}
					}
					
					/*
					if (sumFixTh == 0) {
						sumFixTh = sumFixThTemp;
					}
					
					sumTh = sumDinamTh + sumFixTh;
					*/
					
				} else {
					paddPost = parseInt($(this).css('padding-left')) + parseInt($(this).css('padding-right'));
				}
			});
			
			if (sumFixTh == 0) {
				sumFixTh = sumFixThTemp;
			}
					
			sumTh = sumDinamTh + sumFixTh;
			
			var tdPost = widthTable - sumTh - paddPost;
			
			spacerPost.css('width', tdPost + 'px'); 
			
	}


/**
 * Генерирует случайный пароль
 */
function randomPassword() {
	var chars = "abcdefghijkmnpqrstuvwxyzABCDEFGHIJKLMNPQRSTUVWXYZ0123456789";
	var size = 10;
	var i = 1;
	var ret = "";
	while ( i <= size ) {
		$max = chars.length-1;
		$num = Math.floor(Math.random()*$max);
		$temp = chars.substr($num, 1);
		ret += $temp;
		i++;
	}
	return ret;
}

/**
 * Класс, управляющий всплывающим селектором
 */
var Selector = {
	opened: new Array(),

	display: function(id, callback)
	{
		if($('#'+id).css('display') == 'none') {
			for(i in this.opened) {
				$('#'+this.opened[i]).hide();
			}
			$('#'+id).show();
			this.opened.push(id);
		} else {
			for(i in this.opened) {
				$('#'+this.opened[i]).hide();
			}
			this.opened.length = 0;
		}

		if (callback !== undefined) {
			callback.call();
		}
	},

	init: function(id, value)
	{
		if (value === null) {
			var current = $('.selector-wrapper-'+id+' .selector-list a');
		} else {
			var current = $('.selector-wrapper-'+id+' .selector-list a#selector-item-'+id+'-'+value);
		}
		current = current[0];
		value = current.id.split('-')[3];

		this.check(id, value, true);
	},

	check: function(id, value, is_no_display)
	{
		var ele = $('#selector-item-'+id+'-'+value)[0];
		$('#selector-value-'+id)[0].value = value;
		$('.selector-wrapper-'+id+' .selector-checked').html( $(ele).html() );
		$('.selector-wrapper-'+id+' .selector-list li').show();
		$(ele).parent().hide();

		if (is_no_display === undefined || is_no_display == false) {
			this.display(id);
		}

		return false;
	}
}

/**
 * Обеспечение работы выпадающих фильтров
 */
Filter = {
	init : function (elementForPosition, filterElement, offsetTop, offsetLeft) {
		
		if (typeof offsetTop == 'undefined') {
			var offsetTop = 7;
		}
		if (typeof offsetLeft == 'undefined') {
			var offsetLeft = 7;
		}
		offset = elementForPosition.offset();
		filter = filterElement;
		$('div.popdivs').hide();
		filter.css({'top': offset.top - offsetTop + 'px', 'left': offset.left - offsetLeft + 'px'});
		filter.show();
	},
	close : function() {
		$('div.popdivs').hide();
	}
}

/**
 * Вспомогательный класс для управления всплывающим слом SmsUp
 */
var DivSms = {
	/**
	 * Функция Вычисляет координаты позиционирования слоя SmsUp на странице и показывает его
	 * par - объект (картинка) к которой позиционируем слой,
	 * item - id-шник позиционируемого слоя.
	 */
	posit: function(par, item) {
		var view = $('#' + item);
		var img = $(par);
		var offset = img.offset();
		view
			.css({'left': offset.left - 25 + 'px', 'top': offset.top + img.outerHeight() + 4 + 'px'})
			.show();
	}
}

/**
 * Класс управляет чекбоксами
 */

var Checkboxes = {

	chboxes: null,
	//метод проверяет можно ли включать элемент "снять все"
	check: function(ele_check_all, ele_checks) {

		if (ele_checks.filter(":checked").length > 0) {
			ele_check_all
				.removeClass('inactive')
				.addClass('active');
		} else {
			ele_check_all
				.removeClass('active')
				.addClass('inactive');
		}
	},
	//метод снимает галочки со всех переданных checkbox, при нажатии на "снять все"
	uncheckAll: function(ele_check_all, ele_checks) {
		ele_checks.removeAttr('checked');

		ele_check_all
			.removeClass('active')
			.addClass('inactive');
	}
}

var Checkbox = function (ele_checks, main_check) {

	var chboxes = null;
	var main = null;
	var callback = null; 

	var lastChecked= null;

	var groupSelectEnable= true;

	var that = this;
	that.chboxes = ele_checks;
	that.main = main_check;
	if (typeof that.main == 'undefined' && typeof that.chboxes == 'undefined') {
		return;
	}
	//оъявляем действия при клике на главном элементе
	that.main.click(
				function() {
					if (this.checked) {
						that.selectAll();
					} else {
						that.resetAll();
					}
					if (that.callback) {
						that.callback.call(null, this);
					}
				}
			);

	//объявляем действия при нажатии на элементы
	that.chboxes.click(
			function (event) {

				that.groupSelect(event, this);

				if ($(this).is(':checked')) {
					if (that.chboxes.length == that.getChecked()) {
						that.main.attr('checked', true);
					}
				} else {
					that.main.removeAttr('checked');
				}
				if (that.callback) {
					that.callback.call(null, this);
				}
			}
			);
	//функция навешивает callback на клик по checkbox
	that.on_click = function(callback_f) {
		that.callback = callback_f;
	};
	//функция проставляет галочки у всех елементов
	that.selectAll = function() {
		that.chboxes.filter(":enabled").attr('checked', true);
	};

	//функция убирает галочки у всех элементов
	that.resetAll = function() {
		that.chboxes.filter(":enabled").removeAttr('checked');
	};
	//функция возвращает количество выделенных елементов
	that.getChecked = function() {
		return that.chboxes.filter(":checked").length;
	};
	//функция выделяет группы елементов с помошью shift
	that.groupSelect = function(event, element) {
		if (that.groupSelectEnable == false) {
			return;
		}

		if (!that.lastChecked) {
			that.lastChecked = element;
		}
		if (event.shiftKey) {

			var start = that.chboxes.index(element);
			var end = that.chboxes.index(that.lastChecked);
			for (i=Math.min(start,end);i<=Math.max(start,end);i++) {
				that.chboxes[i].checked = that.lastChecked.checked;
			}
		}
		that.lastChecked = element;
	};
	//функция проверяет выделен ли хотябы один элемент
	that.anyCheck = function() {
		return that.getChecked() > 0;
	}
}

/**
 * Класс, управляющий редактируемыми блоками на страницах
 */
var Editable = {

	editors: new Array(),
	keys: new Array(),
	width_corrector: 4,

	init: function() {
		var list = $('.editable-value');
		if (list.length) {
			list.each(function() {
				$(this).click(function() {
					Editable.form(this);
					return false;
				});
			});
		}
	},

	form: function(ele) {
		ele = $(ele);
		parent = ele.parent();

		form = parent.find('.editable-form');
		if (parent.find('.editable-form input').length == 0) {
			id = this.keys.length;
			form[0].id = id;
			form
				.append('<br />')
				.append('<div class="editable-error"></div>')
				.append('<input type="button" class="button editable-save-button" disabled="disabled" value="Сохранить" onclick="Editable.saveForm(\'' + id + '\');" /> ')
				.append('<input type="button" class="button editable-preview-button" value="Предпросмотр" onclick="Editable.previewForm(\'' + id + '\');" /> ')
				.append('<input type="button" class="button editable-close-button" value="Закрыть" onclick="Editable.closeForm(\'' + id + '\');" />');

			var textarea = form.find("textarea")[0];
			this.keys[id] = textarea.name;
			this.editors[id] = new CodeMirror(CodeMirror.replace(textarea), {
			  parserfile: ["tokenizejavascript.js", "parsejavascript.js", "parsecss.js", "parsexml.js", "parsehtmlmixed.js"],
				  path: "/static/js/codemirror/",
				  stylesheet: ["/static/css/codemirror/jscolors.css", "/static/css/codemirror/csscolors.css", "/static/css/codemirror/xmlcolors.css"],
				  tabMode: "shift",
				  indentUnit: 4,
				  undoDepth: 2,
				  disableSpellcheck: false,
				  content: textarea.value,
				  onChange: function() {
					  Editable.hideSaveButton(id);
				  }
			});
			params = parent.find('.editable-params');
			if (params.html() != '') {
				params
					.show()
					.html('<a href="#" class="dotted" onclick="$(this).parent().toggleClass(\'editable-params-active\'); return false;">доступные переменные</a>' +
							'<span class="list">' + params.html() + '</span>');
			}

			var ele_width = Math.max(255, ele.outerWidth());
			form
				.width( ele_width - this.width_corrector )
				.find('textarea, .CodeMirror-wrapping').width( ele_width - (this.width_corrector+2) );
		}

		parent.toggleClass('editable-active');
	},

	closeForm: function(id) {
		var ele = $('#' + id);
		ele.parent().removeClass('editable-active');
	},

	previewForm: function(id) {
		var ele = $('#' + id);
		var textarea = ele.find('textarea');
		var value = this.editors[id].getCode();//textarea[0].value;
		var key = this.keys[id];

		var error_ele = ele.find('.editable-error');
		error_ele.html('<i>секундочку...</i>');

		$.ajax({
			url: '/ajax/admin/previewEditable',
			data: {value: value, key: key},
			type: 'POST',
			dataType: 'json',
			success: function(response) {

				error_ele.html('');
				var error_list = response.error_list;
				var preview = response.preview;
				if (error_list.length > 0) {
					for (i in error_list) {
						error_ele.append(error_list[i] + '<br/>');
					}
				} else {
					$('.editable-item-' + key + ' .editable-value').html(preview);
					Editable.showSaveButton(id);
				}
			}
		});
	},

	saveForm: function(id) {
		var ele = $('#' + id);
		var textarea = ele.find('textarea');
		var value = this.editors[id].getCode();//textarea[0].value;
		var key = this.keys[id];

		$.ajax({
			url: '/ajax/admin/saveEditable',
			data: {value: value, key: key},
			type: 'POST',
			success: function(response) {
				for (var id = 0, ci = Editable.editors.length; id<ci; id++) {
					if (Editable.keys[id] == key) {
						Editable.editors[id].setCode(value);
					}
				}
				$('.editable-item-' + key + ' textarea').each(function() {this.value = value});
			}
		});

		this.closeForm(id);
	},

	showSaveButton: function(id) {
		var ele = $('#' + id);
		ele.find('.editable-save-button')[0].disabled = false;
	},

	hideSaveButton: function(id) {
		var ele = $('#' + id);
		ele.find('.editable-save-button')[0].disabled = true;
	}
}

/**
 * Класс для AJAX'ой загрузки файлов
 */
var uploader = {
	height : 0,
	width : 0,
	autosafe: false,
	entity: 0,
	entityId: 0,
	fileId:0,

	ajax_uploadImage : function() {
		setRequestURI('/data/uploadImage');
		return ajaxUpload('uploadImage', arguments, 'POST');
	},

	ajax_deleteImage : function() {
		if (confirm('Вы действительно хотите удалить эту картинку?')) {
			if (this.autosafe) {
				arguments = new Array($('#img_id').val());
				return ajaxCustomRequest('deleteImage', arguments, 'POST', '/data/deleteImage');
			} else {
				$('#img_delete').val('1').change();
				this.hideImg(true);
			}
		}
	},

	init: function(height, width, autosafe, entity, entityId, fileId) {
		this.height = height;
		this.width = width;
		this.fileId = fileId;

		if (autosafe) {
			this.autosafe = autosafe;
			this.entity = entity;
			this.entityId = entityId;
		}

		uploader.ajax_uploadImage('#reloadImage', 'reloadImage', this.autosafe, this.entity, this.entityId, this.fileId);
		uploader.ajax_uploadImage('#uploadImage', 'uploadImage', this.autosafe, this.entity, this.entityId);
		uploader.ajax_uploadImage('#uploadImagePic', 'uploadImagePic', this.autosafe, this.entity, this.entityId);

	},

	setImg : function(data, fileId, justload) {
		if (fileId) {
			$('#img_id').val(fileId);
			this.fileId = fileId;
			uploader.init(this.height, this.width, this.autosafe, this.entity, this.entityId, this.fileId);
		} else {
			$('#img_id').val('');
		}

		url = makePreviewUrl(data, this.height, this.width);

		$('#preview').attr("src", url);

		$('#img_src').val(data);
		$('#reloadImg').show();
		$('#uploadImg').hide();
	},

	hideImg : function(not_reset) {
		if (not_reset != true) {
			$('#img_src').val('');
			$('#img_id').val('');
		}

		$('#reloadImg').hide();
		$('#uploadImg').show();
	},

	showFileError : function(mess, id) {
		element = $('#' + id);
		var error = getErrorMessage(mess, id, element.width(), element.outerHeight());
		error = '<div class="error">' + error + '</div>';
		$(error).insertAfter('#' + id);
	},

	hideFileError : function(id) {
		element = $('#error-mess-' + id).parent().parent();
		element.remove();
	}
};


/**
 * Класс, для переключения закладок (Вакансии/Резюме) на главной странице
 */
var Main = {

	tab_list: null,
	changeTab: function(entity) {
		if (this.tab_list == null) {
			this.tab_list = $('.inserts-search-block-div .insert');
		}
		this.tab_list.toggleClass('current');

		$('.tab-pie').toggle();
		$('#form-search').attr('action', '/' + entity);

		$.cookie('mainTab', entity, {expires:9000, path:'/', domain:(location.hostname? '.' + /[-a-z0-9]+\.([a-z]+|xn--[-a-z0-9]+)(\.[a-z][0-9]?)?$/i.exec(location.hostname)[0] : '')})

		SearchAutocomplete.serviceUrl = '/suggest/' + entity;
	}
}

/**
 * Класс для управления логотипами компаний на главной и в списке вакансий
 */
var Logos = {

	divs: null,
	hrefs: null,
	search_key: '',
	data: {list: [], search_key: ''},
	show_type: 'main',
	logosAtRow: 0,

	/**
	 * Инициирование подгрузки и отображения логотипов компаний
	 */
	init: function() {
		this.divs = $('#logos-data>div');
		this.hrefs = $('#logos-data>a');

		var company_ids = [];
		if (Logos.data.list == undefined) {
			Logos.data = {list: [], search_key: null};
		}
		this.hrefs.each(function() {
			var id = $(this).text();
			if (Logos.data.list[id] == undefined) {
				company_ids.push(id);
			}
		});

		//Запрашиваем данные для тех компаний, которых еще нет в this.logo_data
		if (company_ids.length > 0) {
			ajaxCustomRequest('', [this.search_key, company_ids], 'POST', '/data/logos/');
		} else {
			Logos.show(Logos.data);
		}
	},

	/**
	 * Получение ответа с даными логотипов
	 */
	proceed: function(response) {
		eval('var data = ' + response);
		this.show(data);
	},

	/**
	 * Отображение данных с логотипами
	 */
	show: function(data) {
		var carousel = $('#mycarousel');

		var divs = [];
		this.divs.each(function(index, ele){
			divs[index] = $(this);
		})

		this.hrefs.each(function(index, ele){
			var a = $(this);
			var div = divs.shift();
			var id = a.text();

			if (Logos.data.list[id] != undefined) {
				data.list[id] = Logos.data.list[id];
			}

			if (data.list[id] !== undefined && data.list[id].cnt > 0) {
				if (Logos.show_type == 'main') {
					Logos.showTypeMain(carousel, div, a, data.list[id]);
				} else {
					Logos.showTypeVacancy(carousel, div, a, data.list[id]);
				}
				a.mouseover(function() {
					var date = new Date();
					date.setSeconds(date.getSeconds()+10);
					$.cookie('search_key', data.search_key, {expires: date, path: '/', domain:(location.hostname? '.' + /[-a-z0-9]+\.([a-z]+|xn--[-a-z0-9]+)(\.[a-z][0-9]?)?$/i.exec(location.hostname)[0] : '')});
				});
			} else {
				a.detach();
			}
		});

		$(document).ready(function () {
			if (carousel.find('li').length > 0) {
				$('.list-vacancies .tr-logos').show();
				js.include('jquery/jquery.jcarousel.0.2.7');
				carousel.jcarousel({
					scroll: 1,
					visible: Math.min(Logos.logosAtRow, 5)
				});

				if (Logos.logosAtRow < 3) {
					$('.item-logo', '#mycarousel').addClass('full');
				} else {
					$('.item-logo', '#mycarousel').removeClass('full');
				}

				if (Logos.logosAtRow <= 5) {
					$('.jcarousel-next-disabled').hide();
					$('.jcarousel-prev-disabled').hide();
				}
			}
		});
	},

	li: null,
	showTypeMain: function(carousel, div, a, item) {
		if (this.li == null) {
			this.li = $('<li></li>');
			this.li.appendTo(carousel);
			if (div !== undefined) {
				div.appendTo(this.li);
			}
			a.appendTo(this.li);

			this.logosAtRow++;
		} else {
			if (div !== undefined) {
				div.appendTo(this.li);
			}
			a.appendTo(this.li);
			this.li = null;
		}
		a.addClass('item-logo');
		a.text('');
		var span1 = $('<span class="image-table"></span>');
		span1.appendTo(a);
		var span2 = $('<span class="image-container"></span>');
		span2.appendTo(span1);
		var img = $('<img src="' + item.logo + '" />');
		img.appendTo(span2);

		span1 = $('<span class="vacancies-count"></span>');
		span1.text(item.cnt + ' ' + item.plural);
		span1.appendTo(a);
	},

	showTypeVacancy: function(carousel, div, a, item) {
		this.li = $('<li></li>');
		this.li.appendTo(carousel);
		if (div !== undefined) {
			div.appendTo(this.li);
		}
		a.appendTo(this.li);

		a.addClass('item-logo');
		a.text('');
		var span0 = $('<span class="logo-count"></span>');
		span0.appendTo(a);
		var span1 = $('<span class="image-table"></span>');
		span1.appendTo(span0);
		var span2 = $('<span class="image-container"></span>');
		span2.appendTo(span1);
		var img = $('<img src="' + item.logo + '" />');
		img.appendTo(span2);

		span1 = $('<span class="vacancies-count"></span>');
		span1.text(item.cnt + ' ' + item.plural);
		span1.appendTo(span0);

		span1 = $('<span class="description"></span>');
		span1.html(item.description);
		span1.appendTo(a);

		this.logosAtRow++;
	}
}

/**
 * Класс, управляющий уведомлениями на главной странице ЛК
 */
var Notice = {
	close: function(id) {
		$('#block-important-message-'+id).remove();
		$.ajax({
			url: '/myroom/messages/setRead/'+id,
			data: {is_read: true},
			type: 'POST'
		});
	}
}

/**
 * Класс, управляющий серыми подсказками в текстовых полях
 */
var GrayHelp = {

	init: function() {
		$('label.under, label.under-search').each(function () {
			var id = $(this).attr('for');
			GrayHelp.proceed($('#'+id));
		});
	},

	proceed: function(ele) {
		if (ele.val() || ele[0] == document.activeElement || ele.attr('disabled')) {
			GrayHelp.focusOn(ele);
		} else {
			GrayHelp.focusOff(ele);
		}
		ele.focus(function() {
			GrayHelp.focusOn(this);
		});
		ele.blur(function() {
			GrayHelp.focusOff(this);
		});
	},

	//Скрывает метку-подсказку при получении полем фокуса
	focusOn: function(element) {
		var elId = $(element).attr('id');
		$("label[for="+elId+"]").hide();
	},

	//Показывает метку-подсказку при потере полем фокуса, если поле пустое
	focusOff: function(element) {
		if ($(element).val() == '') {
			var elId = $(element).attr('id');
			$("label[for="+elId+"]").show();
		}
	}
}

/**
 * Класс, инициирующий перехват нажатий клавиш на страницах
 */
var KeyControl = {

	init: function() {
		document.onkeydown = function(e) {
			if (!e) e = window.event;
			var k = e.keyCode;

			if (e.ctrlKey) {
				//Ctrl+влево, Ctrl+вправо управляют пейджером, если он есть
				if (k == 37) {
					d = $('#previous_page');
				} else if (k == 39) {
					d = $('#next_page');
				} else {
					d = null;
				}
				if (d && d.length > 0) {
					location.href = d.attr('href');
				}
			} else if (k == 27) {
				//Esc - закрывает открытые всплывающие слои
				outDiv = 1;
				closeDivBody();
			}
		}
	}
}

/**
 * Класс, обрабатывающий форму написания жалобы модератору
 */
var Moderator = {

	form_id: '#moderator-',
	text: new Array('секундочку...', 'Сообщение отправлено'),

	init: function(ele, prefix) {
		offset = $(ele).offset();
		var wrapper = $(this.form_id + 'wrapper' + prefix);
		wrapper.show();
		wrapper.css({top: offset.top - 8 + 'px', left: offset.left - 8 + 'px'});
	},

	close: function(prefix) {
		var wrapper = $(this.form_id + 'wrapper' + prefix);
		$(this.form_id + 'form-message').val('');
		wrapper.hide();
	},

	post: function(prefix) {
		
		var data = {
			email: $(this.form_id + 'form-email' + prefix).val(),
			type: $(this.form_id + 'form-type' + prefix).val(),
			message: $(this.form_id + 'form-message' + prefix).val(),
			entity: $(this.form_id + 'form-entity' + prefix).val(),
			id: $(this.form_id + 'form-id' + prefix).val(),
			form_id: this.form_id
		}
				
		$(this.form_id + 'result' + prefix)
					.removeClass('moderator-result-ok')
					.removeClass('moderator-result-error')
					.css('font-style', 'italic')
					.html(this.text[0]);
		
		$(this.form_id + 'form-button' + prefix).attr('disabled', true);

		$.ajax({
			url: '/data/moderatorWrite/',
			data: data,
			type: 'POST',
			success: function(response) {
				Moderator.result(response, prefix);
				$('.button').removeAttr('disabled');
			}
		});
	},

	setData: function(id, entity) {
		$(this.form_id + 'form-id').val(id);
		$(this.form_id + 'form-entity').val(entity);
	},

	result: function(response, prefix) {
		
		var result = $(this.form_id + 'result' + prefix);
		if (response != '') {
			result.html(response);
			$('.button').removeAttr('disabled');
			
			result
				.removeClass('moderator-result-ok')
				.addClass('moderator-result-error');
		} else {
			result
				.html(this.text[1])
				.removeClass('moderator-result-error')
				.addClass('moderator-result-ok');

				$(this.form_id + 'wrapper' + prefix)
					.delay(4000)
					.slideUp('slow');
				
				this.close();
		}
	}
}

/**
 * Класс для управления Всплывающими Слоями (Авторизации, Написать модератору)
 
	 modalElement - id всплывающего слоя
	 showElement - признак, показывать элемент или нет (true or false)
	 offsetTop - отступ сверху (если не задан или значение 'center' - центрируем по вертикали относительно окна браузера)
	 offsetLeft - отступ слева (если не задан или значение 'center' - центрируем по горизонтали относительно окна браузера)
 */
var showModal = {
	init : function (modalElement, showElement, offsetTop, offsetLeft) {
		
		var modal = $('#' + modalElement);

		if (typeof offsetTop == 'undefined' || offsetTop == 'center') {
			var heightWindow = $(window).height() / 2;
			var heightModal = modal.outerHeight(true) / 2;
			offsetTop = heightWindow - heightModal;
		}
		if (typeof offsetLeft == 'undefined' || offsetLeft == 'center') {
			var widthWindow = $(window).width() / 2;
			var widthModal = modal.outerWidth(true) / 2;
			offsetLeft = widthWindow - widthModal;
		}

		if (String(offsetLeft).indexOf('%') != -1) {
			modal.css({ left: offsetLeft });
		}
		else {
			modal.css({ left: offsetLeft + 'px' });
		}

		var isIE6 = window.ActiveXObject && window.navigator.userProfile;

		var scrollTopIE6 = 0;

		if (isIE6) { // если IE6

			scrollTopIE6 = $(window).scrollTop();

		} 

		modal.css({ top: offsetTop + scrollTopIE6 + 'px' });

		if (showElement == true) {
			$('div.popdivs').hide();

			if (isIE6) { // если IE6

				if ($('iframe.hide-sel-frame')) {
					$('iframe.hide-sel-frame').remove(); // удаляем все iframe.hide-sel-frame
				}

				modal.prepend('<iframe class="hide-sel-frame" src="javascript:\'\';" scrolling="no" frameborder="0" ></iframe>'); // создаем iframe для скрытия select в IE6

			}

			modal.show();
		}
		clearAutoFieldsValues();
		
		// для формы Создания новой компании (Админка)
		if (modal.hasClass('add-company-pb')) {
			$(modal.find('.scroll-company-form')).css('max-height', $(window).height() - 200 + 'px');
		}

	}, 
	close : function() {
		$('div.popdivs').hide();

		clearInterval(clearInt);
		clearInt = 0;

		if (window.ActiveXObject && window.navigator.userProfile) { // если IE6
			if ($('iframe.hide-sel-frame')) {
				$('iframe.hide-sel-frame').remove();
			}
		}
	}
}

/**
 * Функция чистит поля логин и пароль, значения в которые подставляет браузер
 */
clearAutoFieldsValues = function () {
	if (clearInt == 0) {
		clearInt = setInterval(
			function() {
				if ($('#userPassword').val() != "") {
					$("[for=userPassword]").hide();
				}
				if ($('#userLogin').val() != "") {
					$("[for=userLogin]").hide();
				}
			},
		50);
	}
}

/**
 * Класс для переключения табов
 */
var Tabs = {
	tabs: new Array(),
	headers: new Array(),

	init: function() {
		this.tabs = $('.staticTab');
		this.headers = $('.staticPage-tabs .insert');
		this.headers.each(function(index, ele) {
			$(ele).click(function() {
				Tabs.click(index);
				return false;
			});
		});
		this.click(0);
	},

	click: function (n) {
		this.tabs.hide();
		$(this.tabs[n]).show();

		this.headers.removeClass('current');
		$(this.headers[n]).addClass('current');

		return false;
	}
}

/**
 * Класс для открытия вкладок списка
 */
var Tabs2 = {
	inserts: new Array(),
	headers: new Array(),

	init: function() {
		this.inserts = $('.list-static-inserts .descr-insert');
		this.headers = $('.list-static-inserts .title-insert');
		this.headers.each(function(index, ele) {
			$(ele).click(function() {
				Tabs2.click(index);
				return false;
			});
		});
	},

	click: function (n) {
		$(this.inserts[n]).toggle();
		return false;
	}
}

// Set buttons behavior method
var set_buttons_behavior = function(controls) {
	if (controls && !controls.hasClass('disabled')) {
		controls.mouseenter(function() {
			if ($(this).data('mousedown'))
				$(this).addClass('pressed');
		});

		controls.mouseleave(function() {
			if ($(this).data('mousedown'))
				$(this).removeClass('pressed');

			return false;
		});

		controls.mousedown(function() {
			$(this)
				.data('mousedown', true)
				.addClass('pressed');

			return false;
		});

		controls.mouseup(function() {
			$(this)
				.data('mousedown', true)
				.removeClass('pressed');

			return false;
		});

		controls.add('body').mouseup(function() {
			controls.data('mousedown', false);
		});

		controls.click(function() {
			if (!$(this).hasClass('used-as-link'))
				return false; 
		});
	}
}

var InputCharCount = {

	init: function (input_ele, msg_ele) {
		maxlength = input_ele.attr('maxlength');

		$(input_ele).bind('keyup', function() {
			InputCharCount.proceed(input_ele, msg_ele);
  		});

		this.proceed(input_ele, msg_ele);
	},

	proceed: function(input_ele, msg_ele) {
		var length = maxlength - input_ele.val().length;
		if (length < 0) {
			length = 0;
		}
		msg_ele.text(length);
	}
}

var MyRoom = {

	setVisibilityType: function(ele) {
		var ele = $(ele);
		var item = ele.parents('.visib-item');
		var panel = item.find('.visib-panel');
		var parent = ele.parent();

		if (!parent.hasClass('curr')) {
			$.ajax({url: ele.attr('href')});

			var before = panel.find('div:first');
			ele.parent().insertBefore(before);

			panel.find('div.curr').removeClass('curr');
			parent.addClass('curr');

			item.find('a.visib-label').html(ele.html());
		}

		panel.hide();

	},

	noticeRead: function(id) {
		$('#notice-' + id).detach();
		ajaxCustomRequest('', [id], 'POST', '/data/noticeRead');
	}
}

var ErrorBallon = {

	findContainer: function(element) {
		var parent = element.parents('.validate-group:first');
		if (parent.length) {
			findin = parent;
		} else {
			findin = element.parent();
		}
		container = findin.find('.error-container');
		if (!container.length) {
			container = $('<div class="error-container"></div>');
			container.insertBefore(element);
			offset = element.offset();
			positionLeft = element.outerWidth();
			positionTop = 0;

			container.css({
				position: 'relative',
				float: 'left',
				width: 0,
				left: parseInt(positionLeft) + 'px',
				top: parseInt(positionTop) + 'px'
			});
		}

		container_for = element.attr('name').replace(/[\[\]]/g, '-');
		container.addClass(container_for);

		return container;
	},

	findBallon: function(container) {
		ballon = container.find('.ballon');
		if (ballon.length) {
			return ballon;
		};
		id = 'error-mess-' + Math.ceil(Math.random() * 100000);
		html = "<div class='ballon'>" +
				"<div class='error-ballon'>" +
						"<div class='error-ico' onclick='$(\"#"+id+"\").toggle()'></div>" +
						"<div class='error-mess' id="+id+">" +
							"<div >"+
								"<table class='error-shadows'>"+
								"<tr>" +
									"<td class='top-left'></td>"+
									"<td class='top-center'></td>"+
									"<td class='top-right'></td>"+
								"</tr>"+
								"<tr>"+
									"<td class='middle-left'></td>"+
									"<td class='middle-center'>"+
										"<div class='close-div'><div class='close' onclick='$(\"#"+id+"\").hide()'></div></div>"+
										"<div class='error-mess-content'></div>"+
									"</td>"+
									"<td class='middle-right'></td>"+
								"</tr>"+
								"<tr>"+
									"<td class='bottom-left'></td>"+
									"<td class='bottom-center'>"+
									"<div class='corner-div'><div class='bottom-corner'>&nbsp;</div></div>"+
									"<div class='bottom-line'>&nbsp;</div></td>"+
									"<td class='bottom-right'></td>"+
								"</tr>"+
								"</table>"+
							"</div>"+
						"</div>" +
					"</div>" +
					"<div class='ok-ballon ok-ico'></div></div>"
				"</div>";

		ballon = $(html);
		ballon.appendTo(container);

		return ballon;
	},

	getErrorBallon: function(container) {
		ballon = this.findBallon(container);

		return ballon.find('.error-ballon');
	},

	getOkBallon: function(container) {
		ballon = this.findBallon(container);

		return ballon.find('.ok-ballon');
	},

	message: function(msg, element) {

		field = '';
		if (element.id && element.type != 'radio' && element.type != 'checkbox') {
			var label = $('label[for=' + element.id + ']');
			if (label.length && /[A-zА-яёЁ0-9_]+/.test(label.text()) && !label.hasClass('under-search')) {
				field = ' "' + ucfirst(label.text()) + '"';
			}
		}
		return msg.replace(/\{field\}/, field);
	}
}

/**
 * функция скрывающая пустые блоки (баннеры, ssi)
 */
var hideEmptyPlaces = function () {
	$('.jlywny ,' +
		'.xtxltfn ,' +
		'.jmzoed ,' +
		'.ymivj ').each(
			function () {
				if ($(this).children().length == 0 && $(this).parent().length != 0) {
					$(this).hide();
					$('.xtxltfn ').css('margin-bottom', 20);
				}
			}
		);
}

/**
 * Функция, скрывающая пустые места у линейки баннеров (table.t-jmzoed )
 */
var hideEmptyPlacesLine = function () {
			
	var tablePlaces = $('.t-jmzoed ');
			
	tablePlaces.each(function () {
				
		var tdPlaces = $($(this).find('.td-ymivj '));
				
		var numBanns = 0;
				
		tdPlaces.each(function (index) {
			
			if ($(this).children().length == 0) {
						
				$(this).next('.space-td').hide();	
				$(this).hide();
						
			} else {
				numBanns = numBanns + 1;
			}
					
		});
				
		var lastTd = $($(this).find('td:visible:last'));
				
		if (lastTd.hasClass('space-td')) {
			lastTd.hide();
		}
				
		var widthPlace;
				
		if (numBanns == 0) {
			$(this).hide();
		} else {
					
			if (numBanns == 1) { 
				widthPlace = 'auto';
			} else {
				widthPlace = (100 - ((numBanns - 1)* 2)) / numBanns + '%';
			}
				
			tdPlaces.filter(':visible').css('width', widthPlace);
		}
				
	});	
}

/**
 * Добавление/удаление избранных вакансий и резюме в списке (связанное: под текстом вакансии/резюме и справа в списке)
 */
var favorite_toggle = function (show, id) {
	
	$('#add_favor_lnk_' + id).toggle();
	$('#delete_favor_lnk_' + id).toggle();
	
	$('#add_favor_list_' + id).toggle();
	$('#delete_favor_list_' + id).toggle();
	
	$('#add_favor_' + id).toggle();
	$('#delete_favor_' + id).toggle();	

	if (show == 1) {
		$('#add_favor_lnk_'+id).hide(); $('#add_favor_list_'+id).hide();
		$('#delete_favor_lnk_'+id).show(); $('#delete_favor_list_'+id).show();
	}
	if (show == 0) {
		$('#add_favor_lnk_'+id).show(); $('#add_favor_list_'+id).show();
		$('#delete_favor_lnk_'+id).hide(); $('#delete_favor_list_'+id).hide();
	}
}

/**
 * Быстрый выбор города в форме добавления
 */
var quickSelect = function (t) {
	
	var city_id = $(t).attr('rel');
	$('#cities').val($(t).html());

	if (city_id) {
		$('#companyCityId').val(city_id);
		$('#cityId').val(city_id);
		$('#cities').focus();
		
		ajax_getDistricts(city_id);
		setStreetAutocomplete(city_id);

		if (city_id != 826) {
			$('#metro_wrapper').hide();
		} else{
			$('#metro_wrapper').show();
		}
	} else {
		$("#wanted_districts").hide();
		$('#companyCityId').val('');
		$('#cityId').val('');
	}

	return false;
};(function($){var reEscape=new RegExp('(\\'+['/','.','*','+','?','|','(',')','[',']','{','}','\\'].join('|\\')+')','g');function fnFormatResult(value,data,currentValue){var pattern='('+currentValue.replace(reEscape,'\\$1')+')';return value.replace(new RegExp(pattern,'gi'),'<strong>$1<\/strong>');}
function Autocomplete(el,options){this.el=$(el);this.el.attr('autocomplete','off');this.suggestions=[];this.data=[];this.badQueries=[];this.selectedIndex=-1;this.currentValue=this.el.val();this.intervalId=0;this.cachedResponse=[];this.onChangeInterval=null;this.ignoreValueChange=false;this.serviceUrl=options.serviceUrl;this.isLocal=false;this.options={autoSubmit:false,minChars:1,maxHeight:300,deferRequestBy:0,width:0,highlight:true,params:{},fnFormatResult:fnFormatResult,delimiter:null,zIndex:9999,queryType:'jsonp'};this.initialize();this.setOptions(options);}
$.fn.autocomplete=function(options){return new Autocomplete(this.get(0)||$('<input />'),options);};Autocomplete.prototype={killerFn:null,initialize:function(){var me,uid,autocompleteElId;me=this;uid=Math.floor(Math.random()*0x100000).toString(16);autocompleteElId='Autocomplete_'+uid;this.killerFn=function(e){if($(e.target).parents('.autocomplete').size()===0){me.killSuggestions();me.disableKillerFn();}};if(!this.options.width){this.options.width=this.el.width()?this.el.width():300;}
this.mainContainerId='AutocompleteContainter_'+uid;if(this.el.parents('.suggest-box-house').length>0){$('<div id="'+this.mainContainerId+'" style="position:absolute;z-index:9999; width:100%;"><div class="autocomplete-w1"><div class="autocomplete" id="'+autocompleteElId+'" style="display:none; width:300px;"></div></div></div>').appendTo(this.el.parents('.suggest-box-house'));}else{$('<div id="'+this.mainContainerId+'" style="position:absolute;z-index:9999;"><div class="autocomplete-w1"><div class="autocomplete" id="'+autocompleteElId+'" style="display:none; width:300px;"></div></div></div>').appendTo('body');}
this.container=$('#'+autocompleteElId);this.fixPosition();if(window.opera){this.el.keypress(function(e){me.onKeyPress(e);});}else{this.el.keydown(function(e){me.onKeyPress(e);});}
this.el.keyup(function(e){me.onKeyUp(e);});this.el.blur(function(){me.enableKillerFn();});this.el.focus(function(){me.fixPosition();});},parseData:function(txt){suggestion=[];values=[];$.each(txt,function(i,val){suggestion.push("'"+val+"'");values.push("'"+i+"'");});return("{query:'"+this.options.params.q+"',suggestions: ["+Array.prototype.slice.call(suggestion).join(',')+"],data:["+Array.prototype.slice.call(values).join(',')+"]}");},setOptions:function(options){var o=this.options;$.extend(o,options);if(o.lookup){this.isLocal=true;if($.isArray(o.lookup)){o.lookup={suggestions:o.lookup,data:[]};}}
$('#'+this.mainContainerId).css({zIndex:o.zIndex});this.container.css({maxHeight:o.maxHeight+'px',width:o.width});},clearCache:function(){this.cachedResponse=[];this.badQueries=[];},disable:function(){this.disabled=true;},enable:function(){this.disabled=false;},fixPosition:function(){if(this.el.parents('.suggest-box-house').length>0){$('#'+this.mainContainerId).css({top:(0+this.el.innerHeight())+'px',left:0+'px'});}else{var offset=this.el.offset();$('#'+this.mainContainerId).css({top:(offset.top+this.el.innerHeight())+'px',left:offset.left+'px'});}},enableKillerFn:function(){var me=this;$(document).bind('click',me.killerFn);},disableKillerFn:function(){var me=this;$(document).unbind('click',me.killerFn);},killSuggestions:function(){var me=this;this.stopKillSuggestions();this.intervalId=window.setInterval(function(){me.hide();me.stopKillSuggestions();},300);},stopKillSuggestions:function(){window.clearInterval(this.intervalId);},onKeyPress:function(e){if(this.disabled||!this.enabled){return;}
switch(e.keyCode){case 27:this.el.val(this.currentValue);this.hide();break;case 9:case 13:if(this.selectedIndex===-1){this.hide();return;}
this.select(this.selectedIndex);if(e.keyCode===9){return;}
break;case 38:this.moveUp();break;case 40:this.moveDown();break;default:return;}
e.stopImmediatePropagation();e.preventDefault();},onKeyUp:function(e){if(this.disabled){return;}
switch(e.keyCode){case 38:case 40:return;}
clearInterval(this.onChangeInterval);if(this.currentValue!==this.el.val()){if(this.options.deferRequestBy>0){var me=this;this.onChangeInterval=setInterval(function(){me.onValueChange();},this.options.deferRequestBy);}else{this.onValueChange();}}},onValueChange:function(){clearInterval(this.onChangeInterval);this.currentValue=this.el.val();var q=this.getQuery(this.currentValue);this.selectedIndex=-1;if(this.ignoreValueChange){this.ignoreValueChange=false;return;}
if(q===''||q.length<this.options.minChars){this.hide();}else{this.getSuggestions(q);}},getQuery:function(val){var d,arr;d=this.options.delimiter;if(!d){return $.trim(val);}
arr=val.split(d);return $.trim(arr[arr.length-1]);},getSuggestionsLocal:function(q){var ret,arr,len,val,i;arr=this.options.lookup;len=arr.suggestions.length;ret={suggestions:[],data:[]};q=q.toLowerCase();for(i=0;i<len;i++){val=arr.suggestions[i];if(val.toLowerCase().indexOf(q)===0){ret.suggestions.push(val);ret.data.push(arr.data[i]);}}
return ret;},getSuggestions:function(q){var cr,me;cr=this.isLocal?this.getSuggestionsLocal(q):this.cachedResponse[q];if(cr&&$.isArray(cr.suggestions)){this.suggestions=cr.suggestions;this.data=cr.data;this.suggest();}else if(!this.isBadQuery(q)){me=this;me.options.params.q=q;if(me.options.queryType=='jsonp'){$.jsonp({url:this.serviceUrl,data:me.options.params,error:function(xOptions,textStatus){return;},success:function(txt){me.processResponse(me.parseData(txt));}});}else if(me.options.queryType=='json'){$.get(this.serviceUrl,me.options.params,function(txt){me.processResponse(txt);},'text');}}},isBadQuery:function(q){var i=this.badQueries.length;while(i--){if(q.indexOf(this.badQueries[i])===0){return true;}}
return false;},hide:function(){if($.browser.msie&&$.browser.version=="6.0"){$('.iehide').show();}
this.enabled=false;this.selectedIndex=-1;this.container.hide();},suggest:function(){if(this.suggestions.length===0){this.hide();return;}
if($.browser.msie&&$.browser.version=="6.0"){$('.iehide').hide();}
var me,len,div,f,v,i,s,mOver,mClick;me=this;len=this.suggestions.length;f=this.options.fnFormatResult;v=this.getQuery(this.currentValue);mOver=function(xi){return function(){me.activate(xi);};};mClick=function(xi){return function(){me.select(xi);};};this.container.hide().empty();for(i=0;i<len;i++){s=this.suggestions[i];div=$((me.selectedIndex===i?'<div class="selected"':'<div')+' title="'+s+'">'+f(s,this.data[i],v)+'</div>');div.mouseover(mOver(i));div.click(mClick(i));this.container.append(div);}
if($.browser.msie&&$.browser.version=="6.0"){$('.iehide').hide();}
this.enabled=true;this.container.show();},processResponse:function(text){var response;try{response=eval('('+text+')');}catch(err){return;}
if(!$.isArray(response.data)){response.data=[];}
if(!this.options.noCache){this.cachedResponse[response.query]=response;if(response.suggestions.length===0){this.badQueries.push(response.query);}}
if(response.query===this.getQuery(this.currentValue)){this.suggestions=response.suggestions;this.data=response.data;this.suggest();}},activate:function(index){var divs,activeItem;divs=this.container.children();if(this.selectedIndex!==-1&&divs.length>this.selectedIndex){$(divs.get(this.selectedIndex)).removeClass('selected');}
this.selectedIndex=index;if(this.selectedIndex!==-1&&divs.length>this.selectedIndex){activeItem=divs.get(this.selectedIndex);$(activeItem).addClass('selected');}
return activeItem;},deactivate:function(div,index){div.className='';if(this.selectedIndex===index){this.selectedIndex=-1;}},select:function(i){var selectedValue,f;selectedValue=this.suggestions[i];if(selectedValue){this.el.val(selectedValue);if(this.options.autoSubmit){f=this.el.parents('form');if(f.length>0){f.get(0).submit();}}
this.ignoreValueChange=true;this.hide();this.onSelect(i);}},moveUp:function(){if(this.selectedIndex===-1){return;}
if(this.selectedIndex===0){this.container.children().get(0).className='';this.selectedIndex=-1;this.el.val(this.currentValue);return;}
this.adjustScroll(this.selectedIndex-1);},moveDown:function(){if(this.selectedIndex===(this.suggestions.length-1)){this.adjustScroll(0);}else{this.adjustScroll(this.selectedIndex+1);}},adjustScroll:function(i){var activeItem,offsetTop,upperBound,lowerBound;activeItem=this.activate(i);offsetTop=activeItem.offsetTop;upperBound=this.container.scrollTop();lowerBound=upperBound+this.options.maxHeight-25;if(offsetTop<upperBound){this.container.scrollTop(offsetTop);}else if(offsetTop>lowerBound){this.container.scrollTop(offsetTop-this.options.maxHeight+25);}
this.el.val(this.getValue(this.suggestions[i]));},onSelect:function(i){var me,fn,s,d;me=this;fn=me.options.onSelect;s=me.suggestions[i];d=me.data[i];me.el.val(me.getValue(s));if($.isFunction(fn)){fn(s,d,me.el);}},getValue:function(value){var del,currVal,arr,me;me=this;del=me.options.delimiter;if(!del){return value;}
currVal=me.currentValue;arr=currVal.split(del);if(arr.length===1){return value;}
return currVal.substr(0,currVal.length-arr[arr.length-1].length)+value;}};}(jQuery));;(function($){$.fn.popupWindow=function(instanceSettings){return this.each(function(){$(this).click(function(){$.fn.popupWindow.defaultSettings={centerBrowser:0,centerScreen:0,height:500,left:0,location:0,menubar:0,resizable:0,scrollbars:0,status:0,width:500,windowName:null,windowURL:null,top:0,toolbar:0};settings=$.extend({},$.fn.popupWindow.defaultSettings,instanceSettings||{});var windowFeatures='height='+settings.height+',width='+settings.width+',toolbar='+settings.toolbar+',scrollbars='+settings.scrollbars+',status='+settings.status+',resizable='+settings.resizable+',location='+settings.location+',menuBar='+settings.menubar;settings.windowName=this.name||settings.windowName;settings.windowURL=this.href||settings.windowURL;var centeredY,centeredX;if(settings.centerBrowser){if($.browser.msie){centeredY=(window.screenTop-120)+((((document.documentElement.clientHeight+120)/2)-(settings.height/2)));centeredX=window.screenLeft+((((document.body.offsetWidth+20)/2)-(settings.width/2)));}else{centeredY=window.screenY+(((window.outerHeight/2)-(settings.height/2)));centeredX=window.screenX+(((window.outerWidth/2)-(settings.width/2)));}
window.open(settings.windowURL,settings.windowName,windowFeatures+',left='+centeredX+',top='+centeredY).focus();}else if(settings.centerScreen){centeredY=(screen.height-settings.height)/2;centeredX=(screen.width-settings.width)/2;window.open(settings.windowURL,settings.windowName,windowFeatures+',left='+centeredX+',top='+centeredY).focus();}else{window.open(settings.windowURL,settings.windowName,windowFeatures+',left='+settings.left+',top='+settings.top).focus();}
return false;});});};})(jQuery);;
