function LookUp(type, script, singelton)
{
	this.type = type;
	this.script = script;
	
	this.lookupTmst = 0;
	this.lookupTimeOut = 800;
	this.inputLengthLookupStart = 2;
	
	this.singelton = singelton ? 1 : 0;
}

LookUp.prototype.Get = function() {

	// сохраняем время запроса поиска
	oLookUp.lookupTmstSave = oLookUp.GetCurrentMilliseconds();

	var iLookup = $('#inputLookup').get(0);

	if(iLookup.value == iLookup.getAttribute('oldvalue'))
		return false;

	iLookup.setAttribute('oldvalue', iLookup.value);

	if(iLookup.value.length <= oLookUp.inputLengthLookupStart) {
		$('#oLookUpResult').hide('fast');
		return false;;
	}
	
	params = {q: iLookup.value.toLowerCase()};
	oLookUp.LookupAjaxSettings = {
		type: 'GET',
		url: oLookUp.script,
		dataType: 'json',
		data: params,
		success: oLookUp.ShowLookupResults
	};

	setTimeout(function() {
		if(oLookUp.LookupAjaxSettings.data.q && oLookUp.LookupAjaxSettings.data.q.length == $('#inputLookup').val().length) {
			oLookUp.lookupTmst = oLookUp.GetCurrentMilliseconds(-oLookUp.lookupTimeOut);
			if(oLookUp.lookupTmst >= oLookUp.lookupTmstSave) {
				$('#inputLookup').removeClass('pass').addClass('wait');
				$.ajax(oLookUp.LookupAjaxSettings);
			}
		}
	}, oLookUp.lookupTimeOut);

	return false;

}

LookUp.prototype.ClickLookupResult = function(el) {
	var res_cont = $('#lookupItemsResult')
	var id = el.id.split(/_/)[1];
	var str = '<div class="manyItem" id="' + this.type +'_name_' + id + '">' + $(el).html();
	if (!this.singelton) {
		str += '<a href="#" onclick="return oLookUp.Remove(\'' + this.type +'_name_' + id + '\')">[x]</a>';
		str += '<input type="hidden" name="' + this.type +'_ids[]" value="' + id + '" />';
	} else {
		str += '<input type="hidden" name="' + this.type +'_id" value="' + id + '" />';
	}	
	str += '</div>';
	if (this.singelton) {
		res_cont.html('');
	}
	$(str).appendTo(res_cont);
	
	$('#inputLookup').val('');
	$('#oLookUpResult').hide('fast');
	
	return false;
}

LookUp.prototype.Remove = function(id) {
	$('#' + id).remove();
	return false;
}

LookUp.prototype.ShowLookupResults = function(json) {
	//Убираем думалку
	$('#inputLookup').removeClass('wait').addClass('pass');
	
	var str = '';
	if (json.length > 0) {
		for (var i in json) {
			str += '<a href="#" onclick="return oLookUp.ClickLookupResult(this);" id="item_' + json[i].id + '">' + json[i].name + '</a><br/>';
		}
	} else {
		str = 'Данных нет.';
	}
	
	$('#oLookUpResult').show('fast');
	$('#oLookUpResult').html(str);
   	return false;
}



LookUp.prototype.GetCurrentMilliseconds = function(indent) {
	var time = new Date();
	var sec = time.getSeconds().toString();
	var msec = time.getMilliseconds().toString();
	if(indent) {
		msec = msec - indent;
		if(msec < 0) {
			msec = 999 + msec;
			sec--;
		}
	}
	sec = sec.length < 2 ? '0' + sec : sec;
	msec = msec.length < 2 ? '0' + msec : msec;
	msec = msec.length < 3 ? '0' + msec : msec;
	var tmst = time.getMinutes() + sec + msec;
	return tmst;
}
