document.pc_array = [];
pc_toggle_window = function(id, counter){
	var div = $(id);
	//if (div.getStyle('display') == 'block' ) return div.setStyle('display', 'none');
	if (!div.hasClass('d-none'))
		return div.toggleClass('d-none');

	if (!$defined(document.pc_array[counter])){
		document.pc_array[counter] = {};
		div.inject(document.body);
		pc_position_window(div, counter);
		pc_init_first_time(counter);
	}
	div.toggleClass('d-none');
	//div.setStyle('display', 'block');
	if ($defined($('pc_keyword_'+counter))) $('pc_keyword_'+counter).focus();
}

pc_position_window = function(div, counter){
	var coord = $('pc_button_' + counter).getCoordinates();
	div.setStyles({
		top: coord.top + coord.height,
		left: coord.left
	});
}

pc_keyword_change = function (counter)
{
	document.pc_array[counter].timer = $clear(document.pc_array[counter].timer);
	document.pc_array[counter].timer = pc_start_search.delay(300, {'counter': counter});
}

pc_start_search = function(){
	document.pc_array[this.counter].timer = $clear(document.pc_array[this.counter].timer);
	var select = $('pc_select_'+this.counter);
	select.empty();
	var el = new Element('option').setHTML("...LOADING...").setProperty('value', 0).inject(select);
	pc_get_result.delay(10, this, [xajax.getFormValues($('pc_form_'+this.counter)), this.counter] );
}

pc_finish_search = function(users_arr, counter){
	var select = $('pc_select_'+counter);
	select.empty();
	select.addEvent('dblclick', function(e){pc_add(counter);})

	users_arr.each(function(user){
		var el = new Element('option').setHTML(user[1]).setProperty('value', user[0]).inject(select);
	});

	if (users_arr.length == 101){
		var el = new Element('option').setHTML('...more users match...').setProperty('disabled', 'disabled').inject(select);
	}

	if (users_arr.length < 1){
		var el = new Element('option').setHTML('...no results...').setProperty('disabled', 'disabled').inject(select);
	}
}

pc_add = function(counter){
	var arr = [];
	$$('#pc_select_'+counter+' option').each(function(option){
		if (option.selected){
			arr.push({'id': option.value, 'name': option.innerHTML});
		}
	});
	window[$('pc_callback_'+counter).value](arr);
}

pc_add_all = function(counter){
	var arr = [];
	if ($$('#pc_select_'+counter+' option').length == 102){
		alert("There are too much users to add. Reduce result list.");
		return;
	}
	$$('#pc_select_'+counter+' option').each(function(option){
		if (!option.disabled){
			arr.push({'id': option.value, 'name': option.innerHTML});
		}
	});
	window[$('pc_callback_'+counter).value](arr);
}
