var formState = {};
formState.changed = false;
$(function(){
	var menu = $("#menu");
	var personalMenu = $("#personal-menu");


	$(personalMenu).bind("mouseover", function(){
	  personalMenu.next().show();
	});
	$(personalMenu).parent().bind("mouseleave", function(){
	  personalMenu.next().hide();
	})

	var search = $("#search");
	UserNavigation(menu);
	UserNavigation($("#content-menu"))
	siteSearch(search, menu);
	
	futRating();
	//tabbedList("company-vacancy-list");
	 
  //var formElements = getFormState();
  
	init();
	initAutocomplete();
	//initEditableBlock();
	if( $.fn.tooltip )
		$(".tooltip").tooltip();	
	$("embed").attr("wmode", "transparent").css({"position" : "relative"})

	demoSearch();
	inputHelper();
	metaHelper();
	setKeywordAsHref();
  //$(".auth form").append('<input type="hidden" value="true" name="has_js" id="has_js" />');

	//formUnload(formElements);

  if(jQuery.browser.msie)
	  ieFix();
	  
	listOpener($("#fut-rating-full-list"));
});

/*
function sameHeight()
{
  var blocks = new Array();
  var ce;
  var mh = 0;
  for(var i = 0; i < arguments.length; i++)
  {
    ce = document.getElementById(arguments[i]);
    blocks[blocks.length] = ce;
    //blocks[blocks.length].h = ce.offsetHeight();
    if(ce.clientHeight() > mh)
      mh = ce.clientHeight();
  }
  
  for(i = 0; i < blocks.length; i++)
  {
    blocks[i].style.height = mh;
  }
}
*/

function ieFix()
{
  var submenu = $("#navigation-panel .submenu, #content-menu .submenu");
  submenu.each(function(){
    $(this).css({"width" : $(this).width()});
    $(this).find(".bottom").css({"width" : $(this).width() - 3})
  })
}

function siteSearch(search, menu)
{
	var searchInput = search.find("#search-input");
  searchForm = $("#search-form");
	if(searchInput.val())
		search.addClass("not-empty");

	var searchDropdown = $("#search-dropdown");
	var searchDropdownList = searchDropdown.find(".dropdown-list");
	var searchDropdownItems = searchDropdown.find("li a");
	var searchType = searchDropdown.find("#search-type");

	var sOn = false;
	var hideDropDown = true;
  
	function hideSearch()
	{
		menu.show();
		search.removeClass("open");
		searchDropdown.hide();
	}

	function showDropDown()
	{
		if(hideDropDown) return;
		searchDropdownList.show();
	}
  
	searchType.click(function(){
		hideDropDown = false;
		searchInput.focus();
		showDropDown();
	});
  
	searchInput.focus(function(){
		menu.hide();
		search.addClass("open");
		searchDropdown.show();
		showDropDown();
	});
	
	searchDropdownItems.click(function(event){
	  event.preventDefault();
		hideDropDown = true;		
		searchForm.attr("action", $(this).attr("rel"));
		searchDropdownItems.removeClass("selected");
		$(this).addClass("selected");
		searchType.text($(this).text());
		searchDropdownList.hide();
		searchInput.focus();
	});
  
	search.bind("mouseenter", function(){
		sOn = true;
	})

	search.bind("mouseleave", function(){
		sOn = false;
	})

	searchInput.blur(function(){
		if(sOn || searchInput.val()) return;
		search.removeClass("not-empty");
		hideSearch();
		hideDropDown = false;
		sOn = true;
	});
	
	$("#lets-search").click(function(){
	  searchForm.submit();
	})
}


function UserNavigation(menu)
{
	var menuItems = menu.find("ul .title");
	var submenu = $(menu).find(".submenu"); //$("#menu .submenu");
	submenu.each(function(){
	  $(this).css({"margin-left" : "-" + $(this).width()/2 + "px", "left" : "50%"})
	})
	var currentItem;
	menuItems.mouseover(function(){
		if($(this).next().hasClass("submenu"))
		{
			currentItem = $(this).next();
			currentItem.show();
			currentItem.parents("li").bind("mouseleave", function(){
				currentItem.hide()
			})
		};
      
	})
}

function tabbedList(listId)
{
	var list;
	if(typeof listId == "string")
		list = $("#" + listId);
	else
		list = $(listId);
  
	var tab;
	var tabs = list.find(".tab");
	tabs.live("click", function(){
		tab = $(this);
		if(tab.hasClass("active")) return;
		tabs.removeClass("active");
		tab.addClass("active");
	});
}

function futRating()
{
	var rating = $("#fut-rating-list");
	var ratingItems  = rating.find("a");
	var currentItem;
	ratingItems.hover(
		function(){
			currentItem = $(this).find("img");
			currentItem.show();
		},
		function(){
			currentItem.hide();
		})
}

var isLogin = false;

function loginWithCallback(callback, options, permission)
{
  var url = getUrl("/xlogin");
	if (typeof permission == 'undefined') {
		permission = '';
	}

	var form = $("#login-form-popup");
	var loginForm = $(form).find("#enter-form-popup");

	var callback;
	var applyOptions = function(options)
	{
		var el = $("#" + options.element) || {};
		for(var option in options)
			switch(option)
			{
				case "url" 			: 	window.location = options.url; break;
				case "refresh"		: 	$(form).ajaxComplete(function(){
					history.go(0)
					}); break;
				case "regLink"		: 	 break;
			}
	}
	if(isLogin)
	{
		if(callback && jQuery.isFunction(callback)) {
			callback();
			options && applyOptions(options);
		}
	}
	else
	{
		$(form).bgiframe();
		var dialog = $(form).jqm({
			overlay: 60,
			modal: true,
			autoCenter : true,
			trigger: false
		}).jqmShow();
		$(form).find(".panel").css({
			"width" : (parseInt($(form).width()) - 12)  + 'px'
			});
		$(form).jqmAddClose("#close-dialog-trigger");

		var login = $(form).find("#modal-login");
		var pass = $(form).find("#modal-password");
		var remember = $(form).find("#modal-remember");
		if(options.regLink)
		{
			$("#regUL").show();	$("#regLink").hide();
		}
		else
		{
			$("#regUL").hide(); $("#regLink").show();
		}

		$(loginForm).submit(function() {
			$.post(url, {
				'permission' : permission,
				'signin[username]' : $(login).val(),
				'signin[password]' : $(pass).val(),
				'signin[remember]' : $(remember).val()
				}, function(data){
				if(data == 1 || typeof data == "object")
				{
				  
					$(form).jqmHide();
					isLogin = true;
					if(callback && jQuery.isFunction(callback))
					{
						callback();
					}
					//if(typeof options.refresh == undefined)
					if(data.redirect != undefined && (options == undefined || options.url == undefined))
					{
					  options.url = data.redirect;
					}
					
					options && applyOptions(options);
				}
				else
				{
					$(form).find(".error").css({
						"visibility" : "visible",
						"display" : "block"
					});
					return false;
				}
			}, "json");
			return false;
		});
	}
	return false;
}

if(!window.console)
{
  console = {};
  console.log = function(){};
  if(devMode() == true)
  {
    console.log = function(message){alert('Консоль говорит: \n\n' + message)};
  }
}

function devMode()
{
  return (/_dev/gi).test(document.location);
}

//<![CDATA[
// Включение/отключение возможности отправки формы
function regDisableAgreement()
{
	var submit = $("#form-submit")	;

	if(!$("#agreement").attr("checked"))
	{
	    $(submit).attr("disabled", "disabled");
	    $(submit).addClass("disabled");	
	}    
	
	$("#agreement").click(function(){
	    if(this.checked) {
	        $(submit).removeAttr("disabled");
			$(submit).removeClass("disabled");
	    }
	    else {
	        $(submit).attr("disabled", "disabled");
	        $(submit).addClass("disabled");
	    }
	});
}
var init = function() {
    // Получение фокуса ввода контролом
	/*
    $(":text, :password").focus(function(){
        if (!$(this).hasClass("valid"))
            $(this).addClass("current");
    });

    // Потеря фокуса ввода контролом
    $(":text, :password").blur(function(){
        $(this).removeClass("current");
    });

    $(":text, :password").change(function(){
        $(this).removeClass("current");
    })
	*/  
  var checkboxArr = $("body input.item-checkbox");	
  var checkboxLength = checkboxArr.length;  
  var checkedElements;
  
  checkboxArr.click(function(){
    checkedElements = checkboxArr.find(":checked");
    if(checkboxLength == checkedElements.length)
      $("#checkbox-trigger").attr("checked", true);
  })
  
	$("#checkbox-trigger").click(function(){
	  checkboxArr.attr("checked", $("#checkbox-trigger").attr("checked"));
	  checkedElements = $("input.item-checkbox:checked");
	  checkedElements.click(function(){
	    if(!this.checked)
	      $("#checkbox-trigger").removeAttr("checked");
	  })  
	});
}


function initAutocomplete(remoteUrl)
{

	var ac, select;
	var acLabel
	var acId
	var acName
	var autocompleteData = new Array();

	$(".autocomplete").each(function(){
		ac = this


		if ($(this).hasClass("select")) {
			for (var i = 0, length = this.length; i < length; i++) {
				autocompleteData[i] = this.options[i].text
			}

			acId = $(this).attr("id")
			acName = $(this).attr("name")

			//делаем из селекта инпут-автокомплит, который лежит в лейбле
			ac = $('<input id="' + acId + '" name="' + acName + '" class="input" type="text" />')
			ac = $(ac).insertAfter(this)
			select = this;
			$(ac).autocomplete(autocompleteData, {
				autoFill	: $(this).hasClass("autofill"),
				multiple	: $(this).hasClass("multiple"),
				mustMatch	: false
			})
			$(select).remove();
		}
		else
		{
			$(ac).autocomplete(remoteUrl, {
				autoFill	: $(this).hasClass("autofill"),
				multiple	: $(this).hasClass("multiple")//,
				//mustMatch	: true
			})
		}
	})
}

function checkboxInSelect()
{
	var selection = new Array();
	var p;
	var s;
	var html;
	
	this.init = function(selfId, selectionId)
	{
		p = $("#" + selfId);
		s = $("#" + selectionId);
		selection = this.findSelected();
		
		this.renderSelected(selection);
		
		this.listen();
	}
	
	this.listen = function()
	{
		var ct;
		var renderSelected = this.renderSelected, findSelected = this.findSelected;
		$(p).click(function(e){
			ct = $(e.target)
			if(ct.attr("type") == "checkbox") 
				renderSelected(findSelected());
		})
	}
	
	this.findSelected = function()
	{
		selection = p.find("input:checked");
		return selection;
	}
	
	this.renderSelected = function()
	{
		if(selection.length == 0) return s.html("");
		html = $("<p><strong>Выбрано:</strong> </p>");
		for(var i = 0; i < selection.length; i++)
		{
			if(i != 0)
				html.append(", ");
			html.append($(selection[i]).parent().text());
			
		}
		s.html(html);
	}
	
	
	//взято из Tree - надо переписать и упростить
	this.viewSwitch = function(action)
	{
 		var treeId = $(p).attr("id");

		if(!action || action == undefined)
			switch($(p).css("display"))
			{
				case "none" 	: 	action = "open";
									break;

				case "block" 	:	action = "close";
									break;
			}

		switch(action)
		{
			case "open" 	: 	/* $("#" + treeId + '-close').blur().show(); */
								/* $("#" + treeId + '-open').blur().hide(); */
								$("div.tree-container").hide();
								$("select.tree-select-close").hide();
								$("select.tree-select-open").show();
								$(".ie-fix-iframe").hide();
								$("div.multiselect-container").removeClass("relative")
								$(p).parents("div.multiselect-container").addClass("relative");

								$("#" + treeId + '-close').show();
								$("#" + treeId + '-open').hide();


								$("#" + treeId + "-wrap").show();	
								$(p).parents("li").css({"z-index" : "1000"})
								break;

			case "close" 	:	
								$('select.tree-select-close').hide();
								$('select.tree-select-open').show();
								$(p).parents("div.multiselect-container").removeClass("relative");
								$(p).removeClass("can-hide");
								$(".ie-fix-iframe").hide();						
								$("#" + treeId + "-wrap").hide();


								$(p).parents("li").css({"z-index" : ""})
								break;
		}
	}
	
}

function initTreeview(){


	$(".tree").each(function(){
		if(!$(this).hasClass("tree-is-ready"))
			$(this).treeview({
				collapsed	: $(this).hasClass("show-all") == true ? false : true,
				prerendered	: $(this).hasClass("prerendered") == true ? true : false,
				persist		: $(this).hasClass("cookie") == true ? "cookie" : "location",
				cookieId	: $(this).attr("id")
			});
		$(this).parent().bgiframe();
		$(this).bgiframe();
		$(this).addClass("tree-is-ready");
	});

}

function Tree()
{
	var tree, selectionContainer;
	var selectedArr = new Array();
	var currentGroupChecked = new Array();
	var currentGroupTitle;
	var containerPosition;
	var treeId;
	var selContId;
	var treeElements;
	var checkboxArr;
	var SelectionArr = new Array();
	
	this.init = function(containerId, selectionContainerId, containerPositionId)
	{
		if(!containerId)
		{
			this.collectTrees();
			return false;
		}
		
		treeId = containerId;
		selContId = selectionContainerId;
		
		tree = $("#" + containerId);
		if(!$(tree).hasClass("tree-is-ready") && !$(tree).hasClass("not-tree"))
			$(tree).treeview({
				collapsed	: $(this).hasClass("show-all") == true ? false : true,
				prerendered	: $(this).hasClass("prerendered") == true ? true : false,
				persist		: $(this).hasClass("cookie") == true ? "cookie" : "location",
				cookieId	: $(this).attr("id")
			});

		if($(tree).hasClass("tree-multiselect"))
		{
			this.multiselect(tree, selectionContainerId, containerPositionId)
		}
		var viewSwitch = this.viewSwitch;
/* 		скрытие по выходу мышки за пределы */
/* 		$(tree).parent().bind("mouseleave", function(){ viewSwitch(); }) */
	}

	this.multiselect = function(tree, selectionContainerId, containerPositionId)
	{
		if(selectionContainerId)
			selectionContainer = $("#" + selectionContainerId);
		if(containerPositionId)
			containerPosition = $("#" + containerPositionId);
		
		checkboxArr = tree.find(":checkbox");
		
		this.Listener(tree);
	}

	this.Listener = function(tree)
	{
		var fill = this.fill;
		var findChecked = this.findChecked;
		var render = this.render;
		var processElement = this.processElement;
		treeElements = $(tree).find(":checkbox");
		findChecked(tree);
		fill(selectedArr);
		treeElements.click(function(){
			
			/* findChecked(tree); */
			/* fill(selectedArr); */
			processElement(this);
			render();
		});
		
		var clearSelection = this.clearSelection;
		
		$(tree).bgiframe();
	}

	this.processElement = function(el)
	{
		var parent;
		var index;
		var parent_hi;
		if($(tree).hasClass("tree-cat-select"))
			parent = $(el).parents(".collapsable").find(":checkbox").get(0);
		else
			parent = $(el).parents(".collapsable").find("span.folder");

		var renderTree = function(el, action)
		{
			switch(action)
			{
				case "hi_off" : $(el).removeClass("selected"); break;
				case "hi_on" : $(el).addClass("selected"); break;
			}
		
		}
		
		if(!$(el).attr("checked"))
		{
			if($(el).next().hasClass("folder"))
			{
				if(SelectionArr[$(el).attr("id")].length == 0)
				{
					delete SelectionArr[$(el).attr("id")];
					renderTree($(el).next(), "hi_off");
				}	
				else
					SelectionArr[$(el).attr("id")].catSelected = false;
				$(el).parent("li").find(":checkbox").attr("disabled", false);
			}
			else
			{
				if($(tree).hasClass("tree-cat-select"))
				{
					index = $(parent).attr("id");
					parent_hi = $(parent).next();
				}	
				else
				{
					//вот тут мы получаем индекс от которого все крешится
					index = $(parent).text();
					parent_hi = parent;
				}					

				delete SelectionArr[index][$(el).attr("id")];
				SelectionArr[index].length--;
				if(SelectionArr[index].length == 0)
				{
					delete SelectionArr[index];
					renderTree(parent_hi, "hi_off");
				}
			}
			
			
			return false;
		}
		
		
	
		if($(el).next().hasClass("folder") && $(tree).hasClass("tree-cat-select"))
		{
			if(SelectionArr[$(el).attr("id")] == undefined)
			{
				SelectionArr[$(el).attr("id")] = new Array();
				SelectionArr[$(el).attr("id")].categoryText = $(el).next().text();
				SelectionArr[$(el).attr("id")].length = 0;			
			}
			
			$(el).parent("li").find(".file :checkbox").attr("disabled", "disabled");
			$(el).attr("disabled", false);
			SelectionArr[$(el).attr("id")].catSelected = true;
			renderTree($(el).next(), "hi_on");
		}	
		else
		{	
			if($(tree).hasClass("tree-cat-select"))
			{
				index = $(parent).attr("id");
				parent_hi = $(parent).next();
			}	
			else
			{
				index = $(parent).text();
				parent_hi = parent;
			}
			if(SelectionArr[index] == undefined)
			{
				SelectionArr[index] = new Array();
				
				if($(tree).hasClass("tree-cat-select"))
					SelectionArr[index].categoryText = $(parent).next().text();
				else
					SelectionArr[index].categoryText = $(parent).text();
				SelectionArr[index].length = 0;
				SelectionArr[index].catSelected = false;
			}	
			SelectionArr[index][$(el).attr("id")] = $("label[for=" + $(el).attr("id") + "]").text();
			SelectionArr[index].length++;
			renderTree(parent_hi, "hi_on");
		}
	}
	
	this.render = function()
	{
		$(selectionContainer).empty();
		var output = '';
		var count = 1;
		for(cat in SelectionArr)
		{
			if(SelectionArr[cat].catSelected)
				$(selectionContainer).append("<p><strong>" + SelectionArr[cat].categoryText + "</strong></p>")
			else
			{
				for(itemName in SelectionArr[cat])
				{
					
					if(itemName != "catSelected" && itemName != "categoryText")
					{
						output += SelectionArr[cat][itemName];
						output += count ==  SelectionArr[cat].length ? '' : ', ';
						count++;
					}	
				}
				$(selectionContainer).append("<p><strong>" + SelectionArr[cat].categoryText + "</strong> → " + output + "</p>")
			}
		}
		$(selectionContainer).show();
		$(tree).parent().css({"top" : $(tree).parent().parent().height()})
		$(tree).parent().prev().css({"top" : $(tree).parent().parent().height()})
	}


	//возможно, устарел
	this.findChecked = function(el)
	{
		var collectItems = function(currentGroupChecked, selectedArr)
		{
			currentGroupSelection = new Array();
			var vx = 0;
			$(currentGroupChecked).each(function(){
				/* да, я знаю что так делать плохо. я исправлюсь) */
				currentGroupSelection.push(' ' + $('label[for=' + $(this).attr("id") + ']').text());
			});

			return currentGroupSelection;
		}

		if($(el).hasClass("not-tree"))
		{
			currentGroupChecked = $(el).find(":checked");

			selectedArr = new Array();
			currentGroupSelection = new Array();
			selectedArr["Выбрано"] = collectItems(currentGroupChecked, selectedArr);

			return el;
		}

		$(el).find("li > ul").each(function(){
			currentGroupChecked = $(this).find(":checked");
			currentGroupTitle = $(this).parent().find(".folder").text();
			$(this).parent().find(".folder").removeClass("selected");
			if(currentGroupChecked.length)
			{
				$(this).parent().find(".folder").addClass("selected");
				currentGroupSelection = new Array();
				currentGroupSelection = collectItems(currentGroupChecked, selectedArr);
				if(!selectedArr[currentGroupTitle])
					selectedArr[currentGroupTitle] = new Array();

				selectedArr[currentGroupTitle] = currentGroupSelection;
				currentGroupSelection = null;
			}
			else
				if(currentGroupTitle && selectedArr[currentGroupTitle])
					delete selectedArr[currentGroupTitle];
		});
		return el;
	}

	//возможно, устарел
	this.fill = function(selectedArr)
	{
		if(!selectedArr)
			return false;

		if(!selectionContainer)
		{
			selectionContainer = $('<div class="multiselect-selection-container"></div>');
			if(!containerPosition)
				$(tree).before(selectionContainer);
			else
				$(selectionContainer).insertAfter(containerPosition);
		}


		$(selectionContainer).empty();
		var elements = "";
		for(var title in selectedArr)
		{
			if(selectedArr[title] != '')
				$(selectionContainer).append('<p><strong>' + title + '</strong> → ' + selectedArr[title] + '</p>');
		}

		$(selectionContainer).show();
	}
	
	this.clearSelection = function()
	{
		$(selectionContainer).empty();
		for(category in SelectionArr)
		{
			$("#" + category).attr("checked", false);
			$("#" + category).parent("li").find(".file :checkbox").attr("disabled", false);
			for(item in SelectionArr[category])
				$("#" + item).attr("checked", false)
		}
		SelectionArr.clear;
		delete SelectionArr;
		SelectionArr = new Array();
		this.render
	}
	
	this.collectTrees = function()
	{
		init = this.init;
		$(".tree-multiselect").each(function(){
			init($(this));
		})
	}

	this.viewSwitch = function(action)
	{
/* 		var treeId = $(tree).attr("id"); */

		if(!action || action == undefined)
			switch($(tree).css("display"))
			{
				case "none" 	: 	action = "open";
									break;

				case "block" 	:	action = "close";
									break;
			}

		switch(action)
		{
			case "open" 	: 	/* $("#" + treeId + '-close').blur().show(); */
								/* $("#" + treeId + '-open').blur().hide(); */
								$(".tree-container").hide();
								$(".tree-select-close").hide();
								$(".tree-select-open").show();
								$(".ie-fix-iframe").hide();
								$(".multiselect-container").removeClass("relative")
								$(tree).parents(".multiselect-container").addClass("relative");
								$("#" + treeId + '-close').show();
								$("#" + treeId + '-open').hide();
								$("#" + treeId + "-wrap").show();
								
								
								$(tree).parents("li").css({"z-index" : "1000"})
								break;

			case "close" 	:	
								$("#" + treeId + '-close').hide();
								$("#" + treeId + '-open').show();
								$(".tree-select-close").hide();
								$(".tree-select-open").show();
								$(tree).parents(".multiselect-container").removeClass("relative");
								$(tree).removeClass("can-hide");
								$(".ie-fix-iframe").hide();						
								$("#" + treeId + "-wrap").hide();
								
								
								$(tree).parents("li").css({"z-index" : ""})
								break;
		}
	}

	this.tree = tree;
}

function initAddableEducation()
{
	var block, aoriginal

	$("#main").listen( 'click', '.add', function(){

		original = $(this).parent().get(0)
		block = $(original).clone()
		$(block).insertAfter(original)
	})
}

function addableEducation(type)
{
	var educationTemplate = new Object()
	educationTemplate.university = $('<>')
	this.add = function(){

	}
}


function Places(url, idArr, params)
{
	//в этом объекте будут лежать части местоположения
	var place = new Object();
	var idForAc = new Array();

	if(idArr.length == 0 || (url == "" || url == undefined || url == null))
		return false;

	var re = /_[a-z]+$/i;
	var dist;

	for (var i = 0; i < idArr.length; i++)
	{
		dist = idArr[i].match(re);
		dist = dist[0].substring(1, dist[0].length);
		place[dist] = $("#" + idArr[i]);
	}

	this.init = function(cityArr)
	{
		if(cityArr != null && cityArr.length != 0)
		{
			var acArr = new Array();
			for(var element in place)
				if($(place[element]).hasClass("input"))
				{
					/*
					for(var i = 0; i < cityArr.length; i++ )
						acArr[i] = cityArr[i].city;
					$(place[element]).autocomplete(acArr);
					*/
					this.fill(element, cityArr, "city");
				}
		}

		//вызываем метод для отслеживания изменений в контроллах
		this.changeListener();
	}

	this.changeListener = function()
	{
		var fill = this.fill, ajax = this.ajax, hide = this.hide;
		var count = 0;
		for(var element in place)
		{
			if(count == idArr.length - 1)
				break;

			if($(place[element]).hasClass("select"))
				$(place[element]).change(function(){
					hide(this);
					ajax(this, fill);
				})
			else
				$(place[element]).result(function(){
					hide(this);
					ajax(this, fill);
				})
			count++;
		}
	}

	this.hide = function(element)
	{
		var hide = true;

		if(params != undefined && params.hide != undefined && params.hide != null)
			hide = params.hide;

		var process = false;
		for(var el in place)
		{
			if($(place[el]).attr("id") == $(element).attr("id"))
			{
				process = true;
				continue;
			}

			if(process)
			{
				if(hide)
					$(place[el]).addClass("hidden");
				$(place[el]).empty();
				$(place[el]).val("");
			}
		}
	}

	this.ajax = function (element, fill)
	{
		var val = $(element).val();

		if(idForAc != undefined)
			if(idForAc[$(element).val()] != undefined)
				val = idForAc[$(element).val()];

		var loader = $('<img src="/images/ajax-loader-circle.gif" alt="" />');
		$(loader).insertAfter($(element));
		$(loader).ajaxStart(function(){
			$(this).show();
		})
		$(loader).ajaxComplete(function(){
			$(this).remove();
		})

		$.getJSON(url, { name: $(element).attr("id"), value : val }, function(data){

			for(var elementType in place)
				if(data[0] != undefined && data[0][elementType] != undefined && data[0][elementType].length != 0)
				{
					fill($(place[elementType]), data, elementType);
					break;
				}
		})
	}

	this.fill = function(element, dataArr, dist)
	{
		switch($(element).hasClass("select") ? "select" : "input")
		{
			case "select" 	:  	var html = "";
								for(data in dataArr)
									html += '<option value="' + dataArr[data].id + '">' + dataArr[data][dist] + '</option>';

								$(element).append(html);
								$(element).removeClass("hidden");
								break;

			case "input" 	:  	$(element).flushCache();
								for (var i = 0; i < dataArr.length; i++) {
									idForAc[dataArr[i][dist]] = dataArr[i].id;
									dataArr[i] = dataArr[i][dist];
								}

								$(element).autocomplete(dataArr, {matchContains : true});
								$(element).removeClass("hidden");
								break;
		}
	}
}

function resumeAction()
{
	var url = ""
	var elementLength;
	this.save = function(element){


		var target, targetId, inputs, container = $('<div class="editable-section"></div>')
		var elements = new Array(), elementNames = new Array(), toAJAX = [new Array()][new Array()]

		targetId = $(element).attr("id").replace("-save", "")
		container = $("#" + targetId + "-saved").children().length == 0 ? $(container).attr("id", targetId + "-saved").insertBefore($("#" + targetId)) : $("#" + targetId + "-saved")

		elements.length = 0;
		elementNames.length = 0;

		target = $("#" + targetId)

		$(container).empty()
		var collapse = new Collapser();
		var elements = collapse.init(element)
		for(i = 0; i < elements.length; i++)
		{
			$(container).append('<p>' + elements[i] + '</p>')
		}
		$(container).append('<span id="' + targetId + '-edit" class="edit like-link">Изменить</span>')

		$(container).show('slow')
		$(target).hide('slow')
		//return false;


		var form = new Object();
		form.self = $("#" + targetId + "-form");
		form.data = $(form.self).serialize();
		form.url = $(form.self).attr("action");
		$.ajax({
			type : "POST",
			url	 : form.url,
			data : form.data,
			success : function(){

			}
		})


		return false;
	}


	this.edit = function(element){
		var target, targetId, inputs, container = $('<div class="section"></div>')
		targetId = $(element).attr("id").replace("-save", "").replace("-edit", "")

		container = $("#" + targetId + "-saved")
		target = $("#" + targetId)

		$(container).hide('slow')
		$(container).remove()
		$(target).show('slow')

		return false;
	}

	this.reset = function(element)
	{

	}

	this.addEducation = function(templateName)
	{
		templateName = templateName.replace("addEducation ", "")
		var template = $("#" + templateName + "-template").clone()

		var target

		target = $("#resume-education .section")
		$(template).attr("id", $(template).attr("id"))

		$(target).append($(template).show())
	}

}

/*
function initEditableBlock()
{
	var element = new resumeAction()



	$("#content").listen("click", ".save", function(){
		element.save(this)
		$("#resume-form form").submit(function(){return false;})
		$(this).submit(function(){return false;})
		return false;
	})


	$("#content").listen("click", ".edit", function(){
		element.edit(this)
		return false;
	})

	$("#content").listen("click", ".addEducation", function(){
		element.addEducation($(this).attr("class"))
		return false;
	})


	$("#content").listen("keyup", ".ac_input", function(e){
		var key = e.charCode ? e.charCode : e.keyCode ? e.keyCode : 0;
		if(key == 13)
			return false;
	})


}
*/
function FullShortSwitcher()
{

	this.init = function(tableId)
	{
		this.switchView($("#" + tableId));
		this.switchCurrentView($("#" + tableId));
	}

	this.switchView = function(table)
	{
		var parent;
		var element;

		parent = $(".switch");		//.find(".view-selector")

		element = $(parent).find("span");
		$(element).click(function() {
			if (!$(this).parents("li").hasClass("selected"));
			{
				parent.find("li").removeClass("selected")
				$(this).parents("li").addClass("selected")
			}
			
			if($(this).hasClass("short-view"))
			{
				$(table).removeClass("full-view").addClass("short-view");
			}
			else
			{
				$(table).addClass("full-view").removeClass("short-view");
			}
		})
	}
	//test
	this.switchCurrentView = function(table)
	{
		var parent;
		var element;

		element = $(table).find("a.switch-view")
		$(element).click(function(){
			$(this).toggleClass("expand")
			parent = $(this).parents("tr").toggleClass("full-view")
		})
	}
}

function searchFilterAction(parent)
{
	var hide = false;
	this.init = function()
	{
		this.showAnother();

	}

	this.showAnother = function()
	{
		$(".show-another").click(function(){
			active = $(this).parent().parent();
			hide = false;
			if($(active).hasClass("active"))
				hide = true;
			$(parent).find("ul").removeClass("active");
			if(hide)
				$(active).removeClass("active");
			else
				$(active).addClass("active");
		})

	}
}

function resumeCollapseAll(formId)
{
	var elements = $("#" + formId).find("button.save");
	var collapser = new Collapser;
	for(var i = 0; i < elements.length; i++)
		collapser.init(elements[i]);
}

/**
 * sub_city - определяет, что мы будем тянуть после того как вытянем город (метро, вуз, школу, ПТУ или вообще ничего)
 *
 */
function getLocationElement(location_id, name, div_id, parent_id, sub_city, use_count, required)
{
	$('#' + div_id + '-loader').show();
	url = '/common/locationNodes?location_id=' + location_id + '&name=' + name + '&sub_city=' + sub_city + '&use_cnt=' + use_count + '&required=' + required;
	if(parent_id) {
		url+= '&parent_id=' + parent_id;
	}
	$('#' + div_id).load(url, [],
		function(){
			$(this).find("select").addClass("select");
			$(this).find("input:text").addClass("input");
			$(this).find("input:text").addClass("demo-data");
			DemoData($(this).find("input:text").attr('id'));
		}
	);
}

// для вузов школ и для ПТУ
function getInstituteElement(city_id, institute_type_id, name, div_id, use_count, required)
{
	$('#' + div_id + '-loader').show();
	url = '/common/instituteNodes?city_id=' + city_id + '&institute_type_id=' + institute_type_id + '&name=' + name + '&use_count=' + use_count + '&required=' + required;
	$('#' + div_id).load(url, [],
		function(){
			$(this).find("select").addClass("select");
			$(this).find("input:text").addClass("input demo-data");
			DemoData($(this).find("input:text").attr('id'));
		}
	);
}

// факультет вынесен в отдельную функцию - уж очень он специфичен
function getFacultyElement(vuz_id, name, div_id, use_count, show_all_checkbox)
{
	$('#' + div_id + '-loader').show();
	url = '/common/facultyNodes?vuz_id=' + vuz_id + '&name=' + name + '&use_count=' + use_count;
   if(show_all_checkbox) {
       url += '&show_all_checkbox=true';
   }
	$('#' + div_id).load(url, [],
		function(){
			$(this).find("select").addClass("select");
			$(this).find("input:text").addClass("input demo-data");
			DemoData($(this).find("input:text").attr('id'));
		}
	);
}

function clearReplies()
{
	$(".reply").hide();
};

function SplitButton(buttonId, selectId)
{
	var splitButton = $("#" + buttonId + " button");
	var splitButtonCaption = $("#" + buttonId + " em.button-field");
	var eventIgnitor = $("#" + buttonId + " .selector");
	var eventTarget = $("#" + selectId);
	var splitButtonData = new Object();
	var form = $(splitButton).parents("form");
	var formId = $(form).attr("id");

	this.init = function(formActionsArr, buttonCaptionsArr)
	{
		if(formActionsArr == null || formActionsArr == undefined)
		{
			$(splitButton).parent().find("em.selector").remove();
			return false;
		}

		eventTarget = this.fill();
		$(eventIgnitor).click(
			function()
			{
				if($(eventTarget).css("display") == "block")
				{
					$(eventTarget).hide();
					$(this).removeClass("split-selector-hover");
					return false;
				}

				$(this).addClass("split-selector-hover");
				$(eventTarget).find("li").hover(function(){$(this).addClass("hover");}, function(){$(this).removeClass("hover");});
				$(eventTarget).bgiframe();
				$(eventTarget).show();
				$(eventTarget).find("li").click(function(){
					$(splitButtonCaption).text($(this).text());
					$(form).attr("action", formActionsArr[splitButtonData[$(this).text()]]);
					$(eventTarget).hide();
					$(eventIgnitor).removeClass("split-selector-hover");
					$(form).submit();
				});
			}
		);

		$(eventTarget).bind("mouseleave", function(){
			$(eventTarget).hide();
			$(eventIgnitor).removeClass("split-selector-hover");
		})

		$(eventIgnitor).hover(
			function()
			{
				$(this).addClass("split-selector-hover");
			},
			function()
			{
				if($(eventTarget).css("display") != "block")
					$(this).removeClass("split-selector-hover");
			}
		);

		$(splitButton).hover(
			function()
			{
				$(this).addClass("split-button-hover");
			},
			function()
			{
				$(this).removeClass("split-button-hover");
			}
		);


		$(splitButton).submit(function(){
			$(this).val(splitButtonData[$(this).val()]);
		});
	}

	this.fill = function()
	{
		var optionArr = $(eventTarget).find("option");

		splitButtonData.value = new Array();
		splitButtonData.text = new Array();

		var eventTargetListView = $("<ul></ul>").hide();
		$(eventTarget).after(eventTargetListView);
		$(eventTargetListView).attr("id", $(eventTarget).attr("id"));
		$(eventTargetListView).attr("name", $(eventTarget).attr("name"));
		$(eventTargetListView).attr("class", "split-button-container");

		for(var i = 0; i < optionArr.length; i++)
		{
			splitButtonData[$(optionArr[i]).text()] = $(optionArr[i]).val();
			$(eventTargetListView).append("<li>" + $(optionArr[i]).text() + "</li>");
		}
		$(eventTarget).remove();

		return eventTargetListView;
	}
}

function SelectToHidden(buttonId, containerId, name)
{

	var currentSelection;
	var selectionContainer = $("#" + containerId);
	var aSelected = new Object();
	aSelected.length = 0;
	
	var dataToHidden = function(data)
	{
		return '<input type="hidden" name="' + data.name + '[]" value="' + data.data + '" />'; 
	}
	

	
/*	
this.add = function(source)
	{
		currentSelection = $(source).find(":selected");
		
		if($(currentSelection).val() != 0 && (!selected[$(currentSelection).val()] || selected[$(currentSelection).val()] == undefined) || selected.visible == false)
		{
			$(selectionContainer).append(
				$('<p>' + $(currentSelection).text() + dataToHidden({"name":name, "data": $(currentSelection).val()}) + '<img src="/images/icons/delete.png" class="png del" alt="Удалить" align="absmiddle" style="margin-left: 10px" class="del" /></p>'));
			selected[$(currentSelection).val()] = true;
			selected.length++;
			selected.visible = true;
			$(source).val("0");
		}
	}
*/
	var del = function(el)
	{
		$(el).parent().remove();
		delete aSelected[$(el).parent().find(":input").val()];
		aSelected.length--;
	}
	
	this.add = function(el)
	{
		var value = el.val(), text = el.text(), html = '';
		
		if(value != 0 && (!aSelected[value] || aSelected[value] == undefined))
			{
				html = dataToHidden({"name":name, "data": value});
				if(aSelected.length == 0){
					$(selectionContainer).html(html);
				}
			}
	}

	this.listen = function()
	{
		var t, add = this.add;
		/*
		$("#" + buttonId).prev().change(function(){
			
		})
		*/
		/*
		$("body").click(function(e){
			if($(e.target).attr("id") == buttonId)
			{
				add($(this).prev().find(":selected"));
			}
		});
		*/
		selectionContainer.click(function(e){
			t = $(e.target);
			if(t.hasClass("icon-delete-item") || t.parent().hasClass("icon-delete-item"))
			{
				del(t);
			}			
		})
	}

	this.init = function()
	{
		selectionContainer.find("input[type=hidden]").each(function(){
			if(!aSelected[$(this).val()] || aSelected[$(this).val()] == undefined)
			{
				aSelected[$(this).val()] = $(this).parent().text();
			}
		});
		this.listen();
	}
	
	this.init();
	
	this.addFirst = function(source)
	{
		var html = '';
		var value;
		var text;
		/*
		$(source).change(function()
		{
			currentSelection = $(source).find(":selected");
			value = $(currentSelection).val();
			text = $(currentSelection).text();
			
			if(value != 0 && (!aSelected[value] || aSelected[value] == undefined))
			{
				html = dataToHidden({"name":name, "data": value});
				if(aSelected.length == 0){
					$(selectionContainer).html(html);
				}
			}
		});
		*/
		$("#" + buttonId).click(function(){
			html = '';
			currentSelection = $(source).find(":selected");
			value = $(currentSelection).val();
			text = $(currentSelection).text();
			/*
			if(value != 0 && (!aSelected[value] || aSelected[value] == undefined))
			{
				html = dataToHidden({"name":name, "data": value});
				if(aSelected.length == 0){
					$(selectionContainer).html(html);
				}
			}
			*/
			if(value != 0 && (!aSelected[value] || aSelected[value] == undefined))
			{
				aSelected[value] = text;
				aSelected.length++;
		
				for(elm in aSelected)
				{
					if(elm != "length")
						html += '<p>' + aSelected[elm] + dataToHidden({"name":name, "data": elm}) + '<span class="icon no-text icon-delete-item"><em></em></span></p>';
				}
				$(selectionContainer).html(html);
				$(source).val("0");
			}
		});
	}

	
}

function DemoData(itemId)
{
	itemId = $("#" + itemId);
	var demoData;

	demoData = $(itemId).val();
	$(itemId).focus(function(){
		if($(itemId).val() == demoData)
			$(itemId).val("");

	});
	$(itemId).blur(function(){
		if($(itemId).val() == "")
			$(itemId).val(demoData);
	});
}

function demoSearch()
{
	var d = $("#search-suggestion");
	if (d.length == 0)
		return false;
		
	var s = $("#vacancy-search-input");
	window.d = d;
	$(d).click(function()
	{
		s.val(d.text());
		s.focus();
	});
}

function ajaxUpdate(url)
{
	$.post(url);
}

function ajaxPut(url, container)
{
	$.post(url, function(data){
		
		if(data)
		{
			container = $("#" + container);	
			$(container).html(data);
		}
	})
}



function metaHelper(item)
{
	var arr;	
	var comment;
	var parent;
	if(typeof item == "object")
		arr = item;
	else
	{
		arr = $("form.form input[type!=file], form.form select, form.form textarea");
	}
	
	$("form.form input[type=file]").parents("div.form-element").addClass("inline-help");
	
	var el;
	$(arr).blur(function(){
		if(!$(this).hasClass("upload") && $(this).parents("li").find("div.help div.text").text() != '')
		{
		    el = $(this).parents("li").find("div.help")
			effectHide(el);
			el.next().css({"display" : "none"});
			$(this).parents("li").css({"z-index" : 1});
		}
	});

	$(arr).focus(function(){
		if(!$(this).hasClass("upload") && $(this).parents("li").find("div.help div.text").text() != '')
			if(!$(this).parents("li").hasClass("validation-error"))
			{
			  el = $(this).parents("li").find("div.help");
			  if(el.find("div.text").text().length == 0)
			    return false;
				effectShow(el);
				el.next().height(el.height() - 20).css({"display" : "block"});
				$(this).parents("li").css({"z-index" : 10000});
			}
	});
	
	var effectShow = function(el)
	{
		$(getEl(el)).show();
	};

	var effectHide = function(el)
	{
		$(getEl(el)).hide();
	}

	var getEl = function(el)
	{
		if(typeof el == undefined)
			return false;

		if(typeof(el) != "object" && typeof(el) == "string")
			el = $("#" + el).length ? $("#" + el) : $("." + el);

		return el;
	}
}

function inputHelper(updateData)
{
 	try {
		var inputHelperContainerArray = $("span.input-helper");
		if(updateData)
			inputHelperContainerArray = $(updateData);
		$(inputHelperContainerArray).bgiframe();

		$(inputHelperContainerArray).find("input").focus(function(){
			$(this).parent().addClass("input-helper-active");
		})

		$(inputHelperContainerArray).find("input").blur(function(){
			if($(this).val() == '')
				$(this).parent().removeClass("input-helper-active");
		})

		$(inputHelperContainerArray).find("label").click(function(){
			$(this).parent().addClass("input-helper-active");
		})

	  if(!updateData)
		  setTimeout('initHideHelpers(inputHelperContainerArray)', 1000);
	}
	catch (e) {}
}

function initHideHelpers(elArr)
{
	var el;
	$(elArr).each(function(){
		el = this;
		if(!$(el).find("input").val().length && !$(el).hasClass("input-helper-active"))
			$(this).parent().removeClass("input-helper-active");
		else
			$(this).parent().addClass("input-helper-active");			
	})
}

function putIframe(elements)
{
	
}

function validateForm(formId, validationRules, validationMessages)
{
	
	//checkPlugin('validate', validateForm.arguments.callee)
    $('#' + formId).validate({
        rules: validationRules
        ,        
		
		messages: validationMessages
		,
		
        success: function(label){
            label.html("&nbsp;").addClass("valid");
        }
    });
    
    if ($("#agreement").attr("checked")) {
        $("#form-submit").removeAttr("disabled");
    }
    else
    	$("#form-submit").attr("disabled", "disabled")
}

function checkCommentOnForm(commentId){
	if ($("#" + commentId).get(0).value){
		return true;
	}else{
		alert("Необходимо ввести Ваше сообщение");
		return false;
	}
}

function setKeywordAsHref()
{
	$("#top-menu a, #extended-search-button").click(
		function()
		{
			
			if($("#search-input").val() != "")
				$(this).attr("href", $(this).attr("href") + "?keywords=" + $("#search-input").val());
		}
	)
}

function ModalWindow(windowId, text, params)
{  
  if(!text || text == undefined)
    text = {}

  if(!params || params == undefined)
    params = {}


  var windowBlock = $('<div class="window" id="' + windowId + '"><div class="corner lt"></div><div class="corner rt"></div><div class="corner lb"></div><div class="corner rb"></div><div class="panel panel-top"></div><div class="panel panel-bottom"></div></div>');
  var windowContent = $('<div class="window-content" id="' + windowId + '-window-content"></div>');
  var windowText = text && text != '' ? text.content : '';
  
  var okButtonText = text.ok && text.ok != '' ? text.ok : "Ок", cancelButtonText = text.cancel && text.cancel != '' ? text.cancel : "Отмена";  
  var controlsBlock = $('<div class="controls"></div>');
  var button = new Object();
  button.ok = $('<button type="submit" class="button"><span><em class="button-field">' + okButtonText + '</em></span></button>');
  button.cancel = $('<button type="reset" class="button"><span><em class="button-field">' + cancelButtonText + '</em></span></button>');
  controlsBlock.append(button.ok, button.cancel);

  windowBlock.append(windowContent);
  windowBlock.append(controlsBlock);
  $("body").append(windowBlock);
  params.modal = params.modal === undefined ? true : params.modal;
  params.overlayClass = params.overlayClass === undefined ? "jqmOverlay" : params.overlayClass;
  windowBlock.jqm({toTop : true, overlay: 60, modal: params.modal, trigger: false, overlayClass : params.overlayClass, autoCenter : true});
  $(button.cancel).click(function(){
    windowBlock.jqmHide();
  });
  var panel = windowBlock.find("div.panel");
  this.show = function(options)
  {
    controlsBlock.show();
    $(button.ok).show();
    $(button.cancel).show();
    if(options && options != undefined)
      for(option in options)
      {
        switch(option)
        {
          case "onlyOk" : if(options.onlyOk == true) $(button.cancel).hide(); break;
          case "onlyCancel" : if(options.onlyCancel == true) $(button.ok).hide(); break;
          case "hideControls" : controlsBlock.hide(); break;
        }
      }

    if(options && options != undefined && options.zIndex != undefined)
    {
      windowBlock.css({"z-index" : options.zIndex});
      windowBlock.prev().css({"z-index" : options.zIndex-1});
    }    
	
    windowBlock.jqmShow();
	panel.width(parseInt(windowContent.outerWidth()) - parseInt(windowContent.css("padding-right")));
  }
  
  this.content = function()
  {
    if(arguments.length > 0)
      windowContent.html(arguments[0]);
    else
      return windowContent.html();
  }
  
  this.content(windowText);
  
  this.callback = function(func)
  {
    button.ok.unbind("click"); 
    windowContent.find(":input").change(function(){if($(this).parents("[skipUnloadWarning=true]").length == 0) formState.changed = true;})
    button.ok.click(function(){func(); windowBlock.jqmHide()});
  }
  
  this.onclose = function(func)
  {
    button.cancel.unbind("click"); 
    button.cancel.click(function(){func(); windowBlock.jqmHide()});
  }  

  this.center = function()
  {
    //windowBlock.css({"margin-top" : "-" + (parseInt(windowBlock.height())/2) + "px", "margin-left" : "-" + (parseInt(windowBlock.width())/2) + "px"})
  }

  this.width = function(width)
  {
    windowBlock.css({"width" : width + 'px'});
  }
  
}


function _Notification()
{
  var notificationBlock = $("#user-notification-block");
  
  this.s = function()
  {
    if(arguments.length > 0)
    {
      this.message(arguments[0]);
      if(arguments[1] && arguments[1] != undefined)
        this.type(arguments[1])
      this.show();
    }
  }
  
  this.message = function()
  {
    if(typeof notificationBlock != undefined || notificationBlock.length == 0)
      var notificationBlock = $("#user-notification-block");
    
    if(arguments.length > 0)
      notificationBlock.text(arguments[0])
    else
      return notificationBlock.text();
  }
  
  this.hide = function()
  {
    notificationBlock.hide();
  }
  
  this.show = function()
  {
    if(typeof notificationBlock != undefined || notificationBlock.length == 0)
      var notificationBlock = $("#user-notification-block");
    notificationBlock.show();
  }
  
  this.type = function()
  {
    if(typeof notificationBlock != undefined || notificationBlock.length == 0)
      var notificationBlock = $("#user-notification-block");
    
    if(arguments.length > 0)
      notificationBlock.addClass(arguments[0])
    else
      return notificationBlock.attr("class").replace(/notification-block/gi, "");
  }
}

var notification = new _Notification();

var inputHelperContainerArray = $("body .input-helper");


var deleteFromSubscription = function(buttonId, subscrType, table)
{
    $("#" + buttonId).click(function()
    {
      var postString = '';
      var sendRequest = function(postString)
      {  
        $.getJSON("/subscrManagement/jsonMassDeliveryAction?type=" + subscrType + "&rtype=DELETE", postString, function(response){
         if(response.result == "success")
         {
            notification.type("success");
            notification.message("Вакансии удалены из рассылки");
            notification.show();
            changeStatus(response.good, "delete");
          }
        })
      }
      sendRequest(prepareRequest($("#" + table).find(":checked:not(#checkbox-trigger)")));
    })
}


var addToSubscription = function(buttonId, subscrType, table){
  var selectedVacancies;
  var modal = new ModalWindow("subscription-info");
  modal.width(350)
  var message;
  var itemsName;
  switch(subscrType)
  {
    case "VACANCY" : itemsName = "Вакансии"; break;
    case "EVENT" : itemsName = "События"; break;
  }
  
  $("#" + buttonId).click(function()
  {
    var postString = '';
    selectedVacancies = $("#" + table + " :checked:not(#checkbox-trigger)");
    var sendRequest = function(postString)
    {  

      $.getJSON("/subscrManagement/jsonMassDeliveryAction?type=" + subscrType + "&rtype=ADD", postString, function(response){
        if(!response || response == '')
          return false;

        switch(response.result)
        {
          case "success" : 
            notification.type("success");
            notification.message(itemsName + " добавлены в рассылку");
            notification.show();
            changeStatus(response.good, "add");
            break;
            
          case "error"   :
            notification.hide();
            modal.content(getMessage(response.bad, response.good));
            if(response.good.length > 0)
            {
              modal.callback(function()
              {
                sendRequest(prepareRequest(response.good, "response"));
              });
            }
            modal.show({"onlyCancel" : !response.good.length});
            modal.center();
            break;
        }
      });          
    }
    
    var getMessage = function(badList, good)
    {
      var goodCount = good.length;
      var wrap = new Object();
      wrap.header = $('<h2 class="header"></h2>');
      wrap.text = $('<span  class="message"></span>');
      wrap.elements = $('<ul  class="elements"></ul>');
      var output = $('<div></div>');
      var message;
      var paymentLinkHtml = '<a href="' + paymentLink + '" target="_blank">пополнить баланс</a>';
      for(element in badList)
      {
        badCount = badList[element].bad.length;
        message = messages[badList[element].reason].text;
        if(typeof messages[badList[element].reason].text == "object")
        {
          message = messages[badList[element].reason].text[1];
          if(goodCount == 0)
            message = messages[badList[element].reason].text[0];
        }
        
        output.append(wrap.header.append(messages[badList[element].reason].header));
        output.append(wrap.text.append(message));
        if(goodCount != 0)
        {
          for(element in good)
            wrap.elements.append('<li>' + $("#" + good[element]).parents("tr").find(".vacancy-item").text() + '</li>');
          
          output.append("<h4>" + messages.add.text + "</h4>");
          output.append(wrap.elements);
        }
      }
      
      return output.html().replace(/%badVacancyCount%/i, badCount).replace(/%goodVacancyCount%/i, goodCount).replace(/%paymentLink%/, paymentLinkHtml);
    }
    
    sendRequest(prepareRequest(selectedVacancies));      
  });

  var messages = {'WAITING' : {'text' : '', 'header' : ''}, 'NO_MONEY' : {'text' : '', 'header' : ''}, 'add' : {'text' : '', 'header' : ''}, 'NOT_CREATED_YET' : {'text' : '', 'header' : ''}, 'NOT_YET' : {'text' : '', 'header' : ''}};

  messages.WAITING.text = new Array();
  messages.WAITING.text[0] = "Выбранные вакансии уже добавлены в очередь на рассылку";
  messages.WAITING.text[1] = "%badVacancyCount% из выбранных вакансий уже добавлены в очередь на рассылку";
  messages.WAITING.header = "Вакансии уже в очереди на отправку";             
  
  messages.NOT_YET.header = "Нельзя добавить"
  messages.NOT_YET.text = "Уже есть в рассылке";
  
  messages.NO_MONEY.text = "На рассылку выбранных вакансий не хватает средств <br/> Вам необходимо %paymentLink%";
  messages.NO_MONEY.header = "Пополните баланс";                    
  
  messages.NOT_CREATED_YET.text = "Необходимо создать событие, что бы добавить его в рассылки";
  
  messages.add.text = "%goodVacancyCount% из выбранных вакансий можно добавить в рассылку";                  
  //messages.add.text = "Можно добавить %goodVacancyCount% вакансий";
}

function changeStatus(elementList, status)
{
  var icon = '';
  switch(status)
  {
    case "add" : icon = '<span class="icon no-text icon-add-to-subscription" title="Добавлена в рассылку"><em></em></span>'; break;
    case "delete" : icon = '<span class="icon no-text icon-delete-from-subscription" title="Удалена из рассылки"><em></em></span>'; break;
    //default : status = ''; break;
  }
  for(var i=0; i < elementList.length; i++)
  {
    $("#" + elementList[i]).parents("tr").find(".mailing-status").html(icon);
    $("#" + elementList[i]).attr("checked", false);
  }  
}

function prepareRequest (data, dataType)
{
  var postString = '';
  switch(dataType)
  {
    case "response" :  $(data).each(function(){postString += '&ids[]=' + this;}); break; 
    default         :  $(data).each(function(){postString += '&ids[]=' + $(this).attr("id");}); break;
  }
  return postString;
}





function formUnload()
{
  if(jQuery.browser.opera)
  {
      opera.setOverrideHistoryNavigationMode('compatible');
      history.navigationMode = 'compatible';
  }
  
  $("form").not("[skipUnloadWarning=true]").submit(function(){
    window.onbeforeunload = null;
    return true;
  })
  
  var message = "Вы внесли изменения, но не сохранили их. Для того чтобы вернуться и сохранить изменения, нажмите «Отмена», в противном случае все последние изменения на этой странице будут потеряны.";
  window.onbeforeunload = function(){	
    if(formState.changed == true)
    {
      return message;
    }
  }
}

//выбор отраслей, профессий, компаний

function positionCenter(container)
{
  container.css({"margin-top" : "-" + (parseInt(container.height())/2) + "px", "margin-left" : "-" + (parseInt(container.width())/2) + "px"})
}

function EconomicBranch(id, container, rules)
{
 var data, dataSelected;
 var variants = $("#" + id + '-list'), selectionContainer = $("#" + container);
 var html = "";
 var itemHtml = "";
 var labelText;

 var itemsLeft = $("#" + id + "-info-block").find(".items-left");
 var maxItems = rules && rules.maxItems != undefined ? rules.maxItems : 6, itemCount = 1;
 var loadData = rules && rules.loadData != undefined ? rules.loadData : '';
 var savePposition = rules && rules.saveTo != undefined ? rules.saveTo : '';
 var idPrefix = rules && rules.idPrefix != undefined ? rules.idPrefix : "economic-branch";
 var namePrefix = rules && rules.namePrefix != undefined ? rules.namePrefix : "economic-branch";
 var currentElement;
 var aCurrSelection = new Array();
 var checkedCount = 0;
 
 
 this.data = function()
 {
   if(arguments.length == 0)
    return data;

   if(typeof arguments[0] == "object") 
    data = arguments[0];
   else
    $.getJSON(arguments[0], function(response){
      if(!response || response == undefined || response == '')
        return false;
      
      data = response;
      return data;
    })
    
    if(typeof arguments[1] != "undefined")  
    { 
     if(typeof arguments[1] == "object") 
     dataSelected = arguments[1];
    else
     $.getJSON(arguments[1], function(response){
       if(!response || response == undefined || response == '')
         return false;

       dataSelected = response;
       return dataSelected;
     })
  }
   generate();
 }
 
 var selectedElements = new Array();
 this.selected = function()
 {
   delete selectedElements;
   selectedElements = new Array();
   if($(selectionContainer).find("li").length > 0)
   {
     $(selectionContainer).find(".element").each(function(){
       if($(this).text() != '')
        selectedElements.push(jQuery.trim($(this).text()))
     });
     return selectedElements;
   }
   else
    return false;
 }
 
 this.data.exist = function()
 {
   if(data == '' || data == null)
     return false;
   else
     return true;
 } 
 
 var generate = function()
 {
   html = '<ul>';
   var checked, count = 0;
   
   for(pair in data)
   {
   	 if(count++ == data.length/2)
	 	html += "</ul><ul>";
     html += '<li><label><input type="checkbox" id="' + idPrefix + '-' + data[pair].id + '" value="' + data[pair].id + '"/>' + data[pair].name + '</label></li>';
   }
   html += '</ul>';
   variants.append(html);
   
   for(pair in dataSelected)
   {
     checked = variants.find("#" + idPrefix + '-' + dataSelected[pair].id);
     addToSelected(checked);
     $(checked).attr("checked", "checked");
     aCurrSelection[idPrefix + '-' + dataSelected[pair].id] = $(checked).attr("checked")
     aCurrSelection.length++;
   }
   listen();
 }
 
 var listen = function()
 {
   variants.find("input[type=checkbox]").click(function(){
     if(aCurrSelection[$(this).attr("id")] === undefined)
     {
       aCurrSelection[$(this).attr("id")] = !$(this).attr("checked");
       aCurrSelection.length++;
     }
     
     if(this.checked)
     {
       addToSelected(this);
       this.defaultChecked = true;
       if(checkedCount == maxItems)
        {
          variants.find("input[type=checkbox]").attr("disabled", true);
          variants.find(":checked").attr("disabled", false);       
          disableAll = true;     
        }
     }
     else
     {
        deleteFromSelection(this)
        if(checkedCount <= maxItems)
        {
         variants.find("input[type=checkbox]").removeAttr("disabled");
         disableAll = false;
        }
        
     }
   })
 }

 var addToSelected = function(element)
 {
   
   if(savePposition)
   {
     $(savePposition).append('<input type="hidden" id="' + $(element).attr("id") + '" name="' + namePrefix + '[]" value="' + $(element).attr("value") + '" />')
   } 
   
   if($("#" + idPrefix + '-selected-' + $(element).attr("id")).length == 0)  
     selectionContainer.append($('<li><em class="element" id="' + idPrefix + '-selected-' + $(element).attr("id") + '">' + $(element).parent().text() + '</em></li>').append(
       $('<span class="icon icon-delete-item delete-from-selection"><em>&nbsp;</em></span>').click(function(){
         deleteFromSelection($("#" + $(this).parent().find(".element").attr("id").replace(new RegExp(idPrefix + '-selected-'), '')), "button");
       })
     ));
   
   var clearSelectionButton = $('<span class="clear-selection">Очистить выбранное</span>');
   clearSelectionButton.click(function(){
     //как низко((
     $(this).remove();
     deleteAllElements();
   });  
   
   checkedCount++;
   if(checkedCount == maxItems)
     {
       variants.find("input[type=checkbox]").attr("disabled", true);
       variants.find(":checked").attr("disabled", false);
     }
    else
      variants.find("input[type=checkbox]").removeAttr("disabled");
   showItemsLeft(checkedCount);
 }
 
 var deleteFromSelection = function(element, type)
 {
   var elementId = $(element).attr("id");
   if(aCurrSelection[elementId] === undefined)
   {
    aCurrSelection[elementId] = type == undefined ? !$(this).attr("checked") : $(this).attr("checked");
    aCurrSelection.length++;
   } 
   
   $(element).removeAttr("checked");

   $(selectionContainer).find("#" + idPrefix + '-selected-' + elementId).parent("li").remove();  
   if(savePposition)
   {
     $(savePposition).find("#" + $(element).attr("id")).remove();
   }  
   $(element).get(0).defaultChecked = false;

   checkedCount--;
   if(checkedCount == maxItems)
     {
       variants.find("input[type=checkbox]").attr("disabled", true);
       variants.find(":checked").attr("disabled", false);
     }
    else
      variants.find("input[type=checkbox]").removeAttr("disabled");
   
   showItemsLeft(checkedCount);   
 }

this.saveSelection = function()
{
  for(elementId in aCurrSelection)
  {
    delete aCurrSelection[elementId];
    aCurrSelection.length--;
  }
}

this.clearSelection = function()
{
  if(aCurrSelection.length == 0)
    return true;
    
  for(elementId in aCurrSelection)
  {
    $("#" + elementId).attr("checked", aCurrSelection[elementId]);
    ie6elm = $("#" + elementId).get(0);
    ie6elm.defaultChecked = aCurrSelection[elementId];
    if(aCurrSelection[elementId])
    {
      addToSelected($("#" + elementId))
    }  
    else
    {
      deleteFromSelection($("#" + elementId))
    }  
    delete aCurrSelection[elementId];
    aCurrSelection.length--;
  }
  if(checkedCount == maxItems)
    {
      variants.find("input[type=checkbox]").attr("disabled", true);
      variants.find(":checked").attr("disabled", false);
    }
   else
     variants.find("input[type=checkbox]").removeAttr("disabled");
     
  
  checkedCount = selectionContainer.find("li").length;
  showItemsLeft(checkedCount);
}

 var showItemsLeft = function(itemsLeftCount)
 {
   if(itemsLeftCount == 0)
     itemsLeft.text("ни одной");
   else
     itemsLeft.text(itemsLeftCount);
     
   if(itemsLeftCount == maxItems)
   {
     $("#" + id + "-info-block").hide();
     $("#" + id + "-success-block").show();
   }
   else
   {
     $("#" + id + "-info-block").show();
     $("#" + id + "-success-block").hide();     
   }
    
 }
}


function SelectFromGroup(groupId, id, container, rules)
{
	
  var data;
  this.data = function()
   {
   	 
     if(arguments.length == 0)
      return data;

     if(typeof arguments[0] == "object") 
      data = arguments[0];
     else
      $.getJSON(arguments[0], function(response){
        if(!response || response == undefined || response == '')
          return false;

        data = response;
        return data;
      })

      if(typeof arguments[1] != "undefined")  
      { 
       if(typeof arguments[1] == "object")
       dataSelected = arguments[1];
      else
       $.getJSON(arguments[1], function(response){
         if(!response || response == undefined || response == '')
           return false;

         dataSelected = response;
         return dataSelected;
       })
    }
	
    generate();
	
   }
   
   var selectedElements = new Object();
   var selectedElementsGroup;
   var selectedElementsGroupId;
   var onlyChilds = rules && rules.onlyChilds != undefined ? rules.onlyChilds : false;
   
   this.selected = function()
   {
     delete selectedElements;
     selectedElements = new Object();
     selectedElementsGroup = '';
     if($(selectionContainer).find("dd").length > 0)
     {
       $(selectionContainer).find("dt").each(function(){
         selectedElementsGroup = $(this).find("strong").text();
         selectedElements[selectedElementsGroup] = new Object();
         selectedElements[selectedElementsGroup].id = $(this).attr("id").replace(new RegExp(groupIdPrefix, 'gim'), '').replace(new RegExp(categoryIdPrefix, 'gim'), '').replace(new RegExp('-', 'gim'), '').replace(new RegExp('selected', 'gim'), '');
         selectedElementsGroupId = $("#" + $(this).attr("id").replace(/selected-/im, ''));
         if(selectedElementsGroupId.find("input[type=checkbox]").length != selectedElementsGroupId.find(":checked").length || onlyChilds)
         {
           selectedElements[selectedElementsGroup].elements = new Array();
           $(this).find("dd").each(function(){
             selectedElements[selectedElementsGroup].elements[jQuery.trim($(this).text())] = $(this).find("em").attr("id").replace(new RegExp(groupIdPrefix, 'gim'), '').replace(new RegExp(categoryIdPrefix, 'gim'), '').replace(new RegExp('-', 'gim'), '').replace(new RegExp('selected', 'gim'), '');
             selectedElements[selectedElementsGroup].elements.length++;
           })
          }
       })
       return selectedElements;
     }
     else
      return false;
   }

   this.data.exist = function()
   {
     if(data == '' || data == null)
       return false;
     else
       return true;
   }

  var category = $("#" + groupId), group = $("#" + id), selectionContainer = $("#" + container);
  
  var windowContainer = category.parents(".window");
    
  var aSelectedItems = new Array(), aGroupSelectedItems = new Array();
  var currentSelection = new Array();
  var html = "";
  var itemHtml = "";
  var currentGroup = null, currentGroupName = null;

  var categoryIdPrefix = rules && rules.categoryIdPrefix != undefined ? rules.categoryIdPrefix : "profession"; 
  var groupIdPrefix = rules && rules.groupIdPrefix != undefined ? rules.groupIdPrefix : "specialnost"; 
  var namePrefix = rules && rules.namePrefix != undefined ? rules.namePrefix : "";
  var categorySelection = rules && rules.categorySelection == true ? true : false;
  var savePposition = rules && rules.saveTo != undefined ? rules.saveTo : false;
  var defaultFormState = new Array();
  var aCurrSelection = new Array();
  var elementId;
  var groupSelection = new Array();
  var checkedCount = 0;
  var variants = $("#" + id);
  var aCheckbox;
  var multiSelect = rules && rules.multiSelect !== undefined &&  rules.multiSelect !== false ? true : false;
  
  var itemsLeft = $("#" + categoryIdPrefix + "-info-block").find(".items-left");
  var maxItems = rules && rules.maxItems != undefined ? rules.maxItems : false, itemCount = 0;
  
  if(rules)
    for(rule in rules)
      switch(rule)
      {
       
      }
  else
    rules = new Object();
    
  var changeGroupIgnitorCaption = function(element)
  {
    var groupId = $(element).parents("ul").attr("id");
    if($(element).parents("ul").find("input[type=checkbox]").length > $(element).parents("ul").find(":checked").length)
    {
      $(element).find("span").text("Выбрать все");
    }  
    else
    {
      $(element).find("span").text("Сбросить выбранное");
    } 
  }
  
  var itemsGroupAction = function(element)
  {
	
    var groupId = $(element).parents("ul").attr("id");
    if(($(element).parents("ul").find("input[type=checkbox]").length > $(element).parents("ul").find(":checked").length))
    {
      $(element).parents("ul").find("input[type=checkbox]").each(function(){
        //deleteFromSelection(this);
        this.checked = true;
        this.defaultChecked = true;
        if(aCurrSelection[$(this).attr("id")] === undefined)
        {
          aCurrSelection[$(this).attr("id")] = !$(this).attr("checked");
          aCurrSelection.length++;
        }        
        addToSelected(this);
      })      
    }  
    else
      if(($(element).parents("ul").find("input[type=checkbox]").length == $(element).parents("ul").find(":checked").length))
      {
        $(element).parents("ul").find("input[type=checkbox]").each(function(){
          this.checked = false;
          this.defaultChecked = false;
          if(aCurrSelection[$(this).attr("id")] === undefined)
          {
            aCurrSelection[$(this).attr("id")] = !$(this).attr("checked");
            aCurrSelection.length++;
          }
          deleteFromSelection(this);        
        })
      }  
     changeGroupIgnitorCaption(element)           
  }
  
  var generate = function()
  {

    var state = '';
    var screenHeight = document.body.clientHeight;
    var categoryList, singleCategory;
    var groupList = "", singleGroup;
	//var elementsObjArr = [];
    //categoryList = $("<ul></ul>");
	categoryList = '<ul>';
    for(pair in data)
    {
      if(data[pair].id === undefined)
      {
        errorStatus = 'bad data';
        return false;
      }  
      
      elementId = categoryIdPrefix + '-' + data[pair].id;
      currentGroup = groupIdPrefix + '-' + elementId;      
      //singleCategory = $('<li><label id="'  + categoryIdPrefix + '-' + data[pair].id + '">' + data[pair].name + '</label></li>');
      categoryList += '<li><label id="'  + categoryIdPrefix + '-' + data[pair].id + '">' + data[pair].name + '</label></li>';
      
	  if(data[pair].children)
      {
        groupList += '<ul id="' + groupIdPrefix + '-' + categoryIdPrefix + '-' + data[pair].id + '" class="child-list">';
        //сделать определеине клика в методе listen
		if(multiSelect)
          groupList += '<li><span class="like-link dashed check-all">Выбрать все</span></li>';
      	
		for(element in data[pair].children)
      	{
        	groupList += '<li><label><input value="' + data[pair].children[element].id + '" type="checkbox" ' + state + ' id="' + groupIdPrefix + '-' + data[pair].children[element].id + '" name="' + groupIdPrefix + '-' + data[pair].children[element].id + '" />' + data[pair].children[element].name + '</label></li>';
      	}
		groupList += '</ul>';
	  }
      
       
      
      if(screenHeight <= 700)
        group.height(400);
      //categoryList.append(singleCategory);   
      //group.append(singleGroup);       
    }
	
    categoryList += '</ul>';
    category.append(categoryList);
    group.append(groupList);
	
	aCheckbox = group.find("input");
	
    for(pair in dataSelected)
     {
       //checked = group.find("#" + groupIdPrefix + '-' + dataSelected[pair].id);
	   checked = $("#" + groupIdPrefix + '-' + dataSelected[pair].id);
		if (checked.length == 0) {
			$("#" + groupIdPrefix + '-' + categoryIdPrefix + '-' + data[pair].id + " :checkbox").each(function(){
				$(this).attr("checked", "checked");
				addToSelected(this);
				$(this).defaultChecked = true;
				aSelectedItems.length++;
			})
		}
		else 
		{	
			$(checked).attr("checked", "checked");
			addToSelected(checked);
		
			checked = $(checked).get(0);
			// фикс ие6 бага : при добавлении через js чекбоксы не отмечаются помечеными
			$(checked).defaultChecked = true;
			aSelectedItems.length++;
		}
     }
    
 
    listen(); 
  }
  
  var listen = function()
  {
    category.find("label").click(function(){
      currentGroupName = jQuery.trim($(this).parent().text());
      
      elementId = $(this);
      currentGroup = $("#" + groupIdPrefix + '-' + elementId.attr("id")); 
      if(!categorySelection)
      {     
        $(".child-list").hide();
        $(".group-list label").removeClass("current");
        elementId.addClass("current");        
        $("#" + groupIdPrefix + '-' + elementId.attr("id")).show();   
      }
    });  
    
	
    //group.find("input[type=checkbox]").click(function(){
	var t;
	
	selectionContainer.click(function(e){
		if($(e.target).hasClass("delete-from-selection") || $(e.target).parent().hasClass("delete-from-selection"))
		{
			deleteFromSelection($("#" + $(e.target).parents("dd").find("em.element").attr("id").replace(new RegExp(categoryIdPrefix + '-selected-'), '')), 1);
		}
	})
	
	group.click(function(e){
	  t = $(e.target);
	  if (multiSelect) {

	  	if(t.hasClass("check-all"))
			itemsGroupAction(t);
	  	changeGroupIgnitorCaption(t)
	  }
	  if (t.attr("type") == "checkbox") {
	  	if (aSelectedItems.length <= maxItems || !maxItems) {
	  		if (aCurrSelection[$(t).attr("id")] === undefined) {
	  			aCurrSelection[$(t).attr("id")] = !$(t).attr("checked");
	  			aCurrSelection.length++;
	  		}
	  		
	  		if (t.attr("checked")) {
	  			addToSelected(t.get(0));
	  		}
	  		else {
	  			deleteFromSelection(t)
	  		}
	  	}
	  }
    })
  }  
  
  var elementsSelectedInGroup = new Array();
  var addToSelected = function(element)
  {
	if(element == undefined)
	{
		return false;
	}
	
    var groupId = $(element).parents("ul").attr("id");
  	
    var groupContainer = $("#selected-" + groupId);
    var checkedGroup = '';
    if(groupContainer.length == 0)
    {      
      groupContainer = $('<dt id="selected-' + groupId + '"><strong>' + $("#" + groupId.replace(new RegExp(groupIdPrefix + '-'), '')).text() + '</strong></dt>');   
      selectionContainer.append(groupContainer);
      $("#" + groupId.replace(new RegExp(groupIdPrefix + '-'), '')).addClass("checked");
    }  
    if($("#" + categoryIdPrefix + '-selected-' + $(element).attr("id")).length == 0){
      groupContainer.append('<dd><em class="element" id="' + categoryIdPrefix + '-selected-' + $(element).attr("id") + '">' + $(element).parent().text() + '</em><span class="icon icon-delete-item delete-from-selection"><em>&nbsp;</em></span></dd>');
        
    
    
    $(element).get(0).defaultChecked = true;
    var clearSelectionButton = $('<span class="clear-selection">Очистить выбранное</span>');
    clearSelectionButton.click(function(){
      //как низко((
      $(this).remove();
      deleteAllElements();
    });  
    
    
    checkedCount++;
	
     if (maxItems && checkedCount == maxItems) {
	 	aCheckbox.disabled = true;
		aCheckbox.attr("disabled", true);
	 	aCheckbox.filter(":checked").removeAttr("disabled");
	 	
	 }
	 else 
	 	if (aCheckbox.disabled) {
	 		aCheckbox.removeAttr("disabled");
			aCheckbox.disabled = false;
	 	}
     showItemsLeft(checkedCount);

    }
    
	
  }
  
  // elementType - тип элемента
  // 1 - кнопка удаления
  // 0 или не передается - сам чекбокс
  var deleteFromSelection = function(element, elementType)
  {
  	
  	
    var elementId = $(element).attr("id");
	elementType = elementType === undefined ? 0 : elementType;
    if(aCurrSelection[elementId] === undefined)
    {
		if(elementType)
     		aCurrSelection[elementId] = !$(this).attr("checked");
		else
			aCurrSelection[elementId] = $(this).attr("checked");
     	aCurrSelection.length++;
    } 
	
    
    $(element).removeAttr("checked");
    $("#" + categoryIdPrefix + '-selected-' + elementId).parent("dd").remove();
  
    if($('#selected-' + $('#' + elementId).parents("ul").attr("id") + " dd").length == 0)  
    {
      $(selectionContainer).find('#selected-' + $('#' + elementId).parents("ul").attr("id")).remove()
      $("#" + $('#' + elementId).parents("ul").attr("id").replace(new RegExp(groupIdPrefix + '-'), '')).removeClass("checked")
    }
    
    $(element).get(0).defaultChecked = false;
    
     checkedCount = checkedCount <= 0 ? 0 : checkedCount-1;
     if (maxItems && checkedCount == maxItems) {
	 	aCheckbox.disabled = true;
	 	aCheckbox.attr("disabled", true);
	 	aCheckbox.filter(":checked").removeAttr("disabled");
	 	
	 }
	 else 
	 	if (aCheckbox.disabled) {
	 		aCheckbox.removeAttr("disabled");
	 		aCheckbox.disabled = false;
	 	}
     showItemsLeft(checkedCount);
     changeGroupIgnitorCaption($(element).parents("ul").find(".check-all"));
	 
	 return false;     
  }

  this.saveSelection = function()
  {
    for(elementId in aCurrSelection)
    {
      delete aCurrSelection[elementId];
      aCurrSelection.length--;
    }
  }
  
  
  this.clearSelection = function()
  {
  	var el, elParent;
    for(elementId in aCurrSelection)
    {
	  el = $("#" + elementId);
	  elParent = el.parents("ul");
      el.attr("checked", aCurrSelection[elementId]);
      el.get(0).defaultChecked = aCurrSelection[elementId];
      if(aCurrSelection[elementId])
        addToSelected(el)
      else
        deleteFromSelection(el)
      
      changeGroupIgnitorCaption(elParent.find("span.check-all"));
      if($('#selected-' + elParent.attr("id") + " dd").length == 0)  
      {
        $('#selected-' + elParent.attr("id")).remove();
        
      }
      delete aCurrSelection[elementId];
      aCurrSelection.length--;
    }
    
  }

  var showItemsLeft = function(itemsLeftCount)
   {
     if(itemsLeftCount == 0)
       itemsLeft.text("ни одной");
     else
       itemsLeft.text(itemsLeftCount);

     if(itemsLeftCount == maxItems)
     {
       $("#" + categoryIdPrefix + "-info-block").hide();
       $("#" + categoryIdPrefix + "-success-block").show();
     }
     else
     {
       $("#" + categoryIdPrefix + "-info-block").show();
       $("#" + categoryIdPrefix + "-success-block").hide();     
     }

   }

  
  var deleteAllElements = function()
  {
    for(groupId in aSelectedItems)
    {
      for(elementItem in aSelectedItems[groupId].items)
        $("#" + aSelectedItems[groupId].items[elementItem]).attr("checked", false);
      delete aSelectedItems[groupId];  
    }  
    currentSelection = aSelectedItems;
    render();
  }  
  
}


//***

//подписка на обновления компании
/*
*   Использование:
*   selectSubscriptionType({"companyName" : "Имя компании", "url" : "УРЛ куда будем аяксить"})
*/

function selectSubscriptionType(params)
{
  params.companyName = params.companyName !== undefined ? params.companyName : '';
  params.companyId = params.companyId !== undefined ? params.companyId : '';
  params.url = params.url != undefined && params.url != '' ? params.url : false;
  params.selection = params.selection != undefined && params.selection.length != 0 ? params.selection : false;
  var modal = new ModalWindow("selectSubscriptionTypeWindow", {"ok" : "Сохранить"});
  var content;
  var data = {};
  content = '<h2>Подписка на обновления компании ' + params.companyName + '</h2>';
  content += '<ul skipUnloadWarning="true">';
  content += '<li><label><input id="vacancySubscr" type="checkbox" class="checkbox selectable" />уведомлять о новых вакансиях</label></li>';
  content += '<li><label><input id="eventSubscr"type="checkbox" class="checkbox selectable" />уведомлять о новых событиях</label></li>';
  content += '<li><label><input id="materialsSubscr" type="checkbox" class="checkbox selectable" />уведомлять о новых материалах компании</label></li>';
  content += '<li><label><input type="checkbox" class="checkbox" id="check-all"/>уведомлять обо всех новостях, связанных с компанией</label></li>';
  content += '</ul>';
  modal.content(content);
  if(params.selection)
  {
    if(params.selection.length == 3)
    {
      $("#check-all").attr("checked", "checked");
    }
    for(el in params.selection)
    {
      $("#" + params.selection[el]).attr("checked", "checked");
      data[params.selection[el]] = true;
    }
    if($("#selectSubscriptionTypeWindow input.selectable").length == $("#selectSubscriptionTypeWindow input.selectable:checked").length)
    {
      $("#check-all").attr("checked", "checked");
    }
    else
    {
      $("#check-all").removeAttr("checked");
    }
  }
  
  var selectSubscriptionTypeContainer = $("#selectSubscriptionTypeWindow");
  
  
  $("#selectSubscriptionType").click(function(){
    modal.center();
    modal.show();
    
    modal.onclose(
      function()
      {
        if(data)
        {
          for(el in data)
          {
            if(data[el])
              $("#" + el).attr("checked", "checked");
            else
              $("#" + el).removeAttr("checked");
          }
        }
        else
          $("#selectSubscriptionTypeWindow input:checkbox").removeAttr("checked");
      }
    );
    modal.callback(
      function()
      {
        data = {};
        $("#selectSubscriptionTypeWindow input.selectable").each(function(){
          if($(this).attr("checked"))
            data[$(this).attr("id")] = true;
          else
            data[$(this).attr("id")] = false;
        });
        
        data.companyName = params.companyName;
        data.companyId = params.companyId;
        $.post(params.url, data);
      }
    )
    return false;
  })

  selectSubscriptionTypeContainer.listen('click', '.checkbox', function(){
    if($(this).attr("id") == "check-all")
    {
      if($(this).attr("checked"))
        $("ul :checkbox", selectSubscriptionTypeContainer).attr("checked", "checked");
      else
        $("ul :checkbox", selectSubscriptionTypeContainer).removeAttr("checked");
    }
    else
    {
      if(!$(this).attr("checked"))
        $("#check-all", selectSubscriptionTypeContainer).removeAttr("checked");
      
      if($("#selectSubscriptionTypeWindow input.selectable").length == $("#selectSubscriptionTypeWindow input.selectable:checked").length)
      {
        $("#check-all").attr("checked", "checked");
      }
      else
      {
        $("#check-all").removeAttr("checked");
      }
    }
    
    if(selectSubscriptionTypeContainer.find(":checkbox:not([id=check-all])").length == selectSubscriptionTypeContainer.find(":checked:not([id=check-all])").length)
    {
      $("#check-all", selectSubscriptionTypeContainer).attr("checked", "checked");
    }
  });
}

function listOpener(list)
{
  if(list.length == 0) return;
  var listNodes = list.find(".item");
  var item;
  list.click(function(event){
    if(!$(event.target).hasClass("opener")) return;
    item = $(event.target).parent();
    if(item.hasClass("closed"))
    {
      item.attr("class", "item opened");
    }
    else
    {
      item.attr("class", "item closed");
    }
  })
}

function getUrl(url)
{
  if(env == 'dev')
    return "/frontend_dev.php" + url;
  else
    return url;
}
//]]>
function st()
{
	return window.pageYOffset != undefined ? window.pageYOffset : document.documentElement.scrollTop;
}
