function moreObjects(url, resultDiv)
{
	jQuery('#' + resultDiv).html('Идет загрузка данных...');

	if ( typeof(jQuery) != "undefined" ) {
		jQuery.post(url, {}, function(data) { jQuery('#' + resultDiv).html(data); });
	}
	else { // не загружена библиотека AJAX
	
	}
}

function showGoogleMap(s) 
{
	var u = "";
	var w = 640;
	var h = 480;
	u = "/spb/term/map/view_google_one.php?d=" + s;
	window.open(u, "_blank","width="+w+",height="+h+",scrollbars=0,resizable=0,menubar=0,toolbar=0");
};

function addComment(intIdObject, intIdBase)
{
	var elComment = document.getElementById('newcomment');
	var strComment = '';
	
	if (jQuery && elComment) {		
		strComment = elComment.value;
		if ( strComment != '' ) {
			$("#example1").html('Обновление данных...')
			jQuery.post('/ajax/getcomments/' + intIdObject + '.html?query=base/' + intIdBase, {comment: strComment, id_base: intIdBase, id_object: intIdObject}, onAjaxSuccess_addComment);
		}
	};
	return false;
}
function onAjaxSuccess_addComment(data) { $('#example1').html(data); };

function updateSelect(strIdSelect, strData, strSepField, strSepRow, strSelectedValue)
{
    var objSelect = document.getElementById(strIdSelect);
	var boolResult = false;
	if ( ( objSelect ) && ( strData.length > 0 ) ) {
		objSelect.options.length = 0;
		var arRows = strData.split(strSepRow); // массив строк
		for (var i = 0; i < arRows.length; i++) {
			arValue = arRows[i].split(strSepField); // массив значений
			objSelect.options[objSelect.options.length] = new Option(arValue[1], arValue[0], false, false);
		}
		
		if ( strSelectedValue != '' ) {
			jQuery('#' + strIdSelect + ' option[@value="' + strSelectedValue + '"]').attr('selected', 1);
		}
		
		boolResult = true;
	}
	return boolResult;
}

function updateSelectAjax(strUrl, strResultSelect, strSelectedValue)
{
	updateSelect(strResultSelect, '0;загрузка данных...', ';', '\n');
	//if ( !jQuery.post(strUrl, {}, function(data) { updateSelect(strResultSelect, data, ';', '\n', strSelectedValue); }) ) {
	if ( !jQuery.get( strUrl, {}, function(data) { updateSelect(strResultSelect, data, ';', '\n', strSelectedValue); }) ) {
		alert('Броузер не смог отправить запрос через JQuery, попробуйте обновить страницу!');
	}
	return true;
}



function updSearch(intIdReg, intIdDept, intIdDist, intIdStreet, intIdStation)
{	
	jQuery('#selectReg option[@value="' + intIdReg + '"]').attr('selected', 1);
	updateSelectAjax('/ajax/getdept2/' + intIdReg + '.html', 'selectDept', intIdDept);
	updateSelectAjax('/ajax/getdist2/' + intIdDept + '.html?query=reg/' + intIdReg, 'selectDist', intIdDist);
	updateSelectAjax('/ajax/getstreet2/' + intIdDist + '.html?query=reg/' + intIdReg, 'selectStreet', intIdStreet);		
	updateSelectAjax('/ajax/getstation/' + intIdDept + '.html?query=reg/' + intIdReg, 'selectStation', intIdStation);
	
	if ( intIdDept == 2 ) {
		jQuery('#labelSelectStation').html('Метро');
		jQuery('#labelSelectDist').html('Район');
	}
	else {
		jQuery('#labelSelectStation').html('Ж/д станция');
		jQuery('#labelSelectDist').html('Нас.пункт');
	}
	
	jQuery('#searchAddressResult').hide();
	jQuery('#fieldSearchAddress').val('');
}

// init



var iTimeoutId = null; // переменная для хранения интервала
var currentOpen = null; // название последнего открытого слоя
	
/* функция отправляет запрос к серверу */
function searchAddress(obj_event)
{
	obj_event = obj_event || window.event;
	txt_field = obj_event.target || obj_event.srcElement;
		
	if (iTimeoutId != null) {
		clearTimeout(iTimeoutId);
		iTimeoutId = null;				
	}
			
	var sObj = new String(txt_field.value);
	if (sObj.length > 1) {
		iTimeoutId = setTimeout("on_time(txt_field)", 500);
	}
}
	
/* функция обработки собития таймера */
function on_time(sea, regValue)
{		
	var sObj = new String(sea.value);
	if (sObj.length > 2) {
		if ( !jQuery.post('/ajax/searchaddress/?query=reg/' + regValue, { sa: sea.value }, function(data) { jQuery('#searchAddressResult').html(data).show(); }) ) {
			alert('Броузер не смог отправить запрос через JQuery, попробуйте обновить страницу!');
		}
	}
	else {
		alert('Поик ведется по 3-м и более символам!');
	}
}

/* функция заменяет запятые */
function replaceComma(strInput) {
	var strResult = strInput;
	var objString = new String(strInput);
	var arTmp = new Array();
	if ( objString.length > 0 ) {
		arTmp = objString.split(",");				
		strResult = arTmp.join(".");
		arTmp = strResult.split(" ");
		strResult = arTmp.join("");
	}
	return strResult;
}

/* функция проверяет форму квартиры/комнаты */
function testFormFlat(isRoom, intUpdateAddress, intIsOperator) {
	var strFormName = "reoForm";
	var em = "";
	var boolResult = false;
	
	em+= tddlBulgakov(strFormName, "agentID","Агент"); 
	if ( intUpdateAddress == 1 ) {
		em+= tddlBulgakov(strFormName, "reg", "Регион"); 
		em+= tddlBulgakov(strFormName, "dept", "Адм.центр"); 

		var intDept = document.forms[strFormName].elements['dept'].value;
		if ( intDept == 2 ) {
			em+= trfn(strFormName, "house_n", "Дом"); 
		}		
	}
	em+= tddlBulgakov(strFormName, "type", "Тип сделки"); 	
	em+= trfn(strFormName, "amountRooms", "Количество комнат"); 
	if ( isRoom == 1 ) {
		em+= trfn(strFormName, "amountRoomsTotal", "Кол-во комнат в квартире (всего)"); 
	}
	em+= trfn(strFormName, "price", "Цена с процентами \n (тыс.руб.)"); 
	em+= testFloatValue(strFormName, "brockerage", "Комисионные", 0); 
	em+= testFloatValue(strFormName, "brockerage50x50", "Наша доля при совместной сделке", 0); 
	em+= testFloatValue(strFormName, "sAll", "Общая площадь", 1); 
	em+= testFloatValue(strFormName, "sLife", "Жилая площадь", 0); 
	em+= testFloatValue(strFormName, "sKitchen", "Площадь кухни", 0); 
	em+= testFloatValue(strFormName, "sCorridor", "Коридор", 0); 
	em+= testFloatValue(strFormName, "sVestibule", "Прихожая", 0); 
	em+= testFloatValue(strFormName, "sCeiling", "Потолок", 0); 
	em+= trfn(strFormName, "floor", "Этаж"); 
	em+= trfn(strFormName, "floorAll", "Этажность"); 
	em+= testFloatValue(strFormName, "firstFloorHeight","Высота 1-го этажа", 0); 
	em+= tnf(strFormName, "leasers", "Съемшиков"); 
	em+= tnf(strFormName, "tenants", "Жильцов"); 
	em+= tnf(strFormName, "children", "Детей"); 
	em+= tnf(strFormName, "yearBuild", "Год постройки"); 
	em+= tnf(strFormName, "yearCapitalRepair", "Кап.ремонт");
	
	if ( intIsOperator == 1) {
	}
	
	if ( em == '') {
		boolResult = true;
		document.forms[strFormName].submit(); 		
	}
	else {
		alert(em);		
	}
	return boolResult;
}

/* функция проверяет форму коммерческая */
function testFormComm(strFormName, intUpdateAddress, intIsOperator) {
	var em = "";
	var boolResult = false;
	
	em+= tddlBulgakov(strFormName, "agentID","Агент"); 
	if ( intUpdateAddress == 1 ) {
		em+= tddlBulgakov(strFormName, "reg", "Регион"); 
		em+= tddlBulgakov(strFormName, "dept", "Адм.центр"); 
	}
	em+= tddlBulgakov(strFormName, "CObjType", "Объект"); 
	em+= trfn(strFormName, "STotal", "Общая площадь"); 
	
	em+= testFloatValue(strFormName, "PriceAr", "Аренда", 0); 
	em+= tnf(strFormName, "PriceS", "Продажа"); 
	em+= tnf(strFormName, "PriceArS", "ППр аренды"); 
	em+= tddlBulgakov(strFormName, "sPriceArCode", "");
	em+= tddlBulgakov(strFormName, "sPriceSCode", "");
	em+= tddlBulgakov(strFormName, "sPriceArSCode", "");
	
	em+= testFloatValue(strFormName, "area", "Земля", 0); 
	em+= tnf(strFormName, "areaArenda", "Аренда (лет)"); 
	em+= tnf(strFormName, "Floors", "");

	if ( intIsOperator == 1) {
	}
	
	if ( em == '') {
		boolResult = true;
		document.forms[strFormName].submit(); 		
	}
	else {
		alert(em);		
	}
	return boolResult;
}

/* функция проверяет форму аренды */
function testFormRent(strFormName, intUpdateAddress, intIsOperator) {
	var em = "";
	var boolResult = false;
	var intDocType = 0;
		
	em+= tddlBulgakov(strFormName, "agentID","Агент"); 
	if ( intUpdateAddress == 1 ) {
		em+= tddlBulgakov(strFormName, "reg", "Регион"); 
		em+= tddlBulgakov(strFormName, "dept", "Адм.центр"); 
	}
	em+= tddl(strFormName, "CObjType", "Объект"); 

	em+= trfn(strFormName, "amountRooms", "Кол-во комнат"); 
	em+= tnf(strFormName, "amountRoomsTotal", "Кол-во комнат всего"); 
	em+= tnf(strFormName, "floor", "Этаж"); 
	em+= tnf(strFormName, "floorAll", "Этажей"); 
	em+= testFloatValue(strFormName, "sLife", "Жилая", 0); 
	em+= testFloatValue(strFormName, "sKitchen", "Кухня", 0); 
	em+= tnf(strFormName, "SleepBed", "Спальных мест"); 
	
	if ( document.forms[strFormName].elements['docType'] ) {
		intDocType = document.forms[strFormName].elements['docType'].value;
	}
	
	if ( ( intIsOperator == 1 ) && ( intDocType > 0 ) ) {
		// проверка валидности дат договора
		em+= tfp(strFormName, "dBegin", "дата начала договора", "^[0-9]{2}\\.{1}[0-9]{2}\\.{1}[0-9]{4}$", "поле \"ДАТА НАЧАЛА ДОГОВОРА\" долженно быть в формате \"дд.мм.гггг\";");
		em+= tfp(strFormName, "dEnd", "дата окончания договора", "^[0-9]{2}\\.{1}[0-9]{2}\\.{1}[0-9]{4}$", "поле \"ДАТА ОКОНЧАНИЯ ДОГОВОРА\" долженно быть в формате \"дд.мм.гггг\";");
	}
		
	if ( em == '') {
		boolResult = true;
		document.forms[strFormName].submit(); 		
	}
	else {
		alert(em);		
	}
	return boolResult;
}

/* функция проверяет форму новостройки */
function testFormBuild(strFormName, intUpdateAddress, intIsOperator) {
	var em = "";
	var boolResult = false;
	var intDocType = 0;
		
	em+= tddlBulgakov(strFormName, "agentID","Агент"); 
	if ( intUpdateAddress == 1 ) {
		em+= tddlBulgakov(strFormName, "reg", "Регион"); 
		em+= tddlBulgakov(strFormName, "dept", "Адм.центр"); 
		em+= tddlBulgakov(strFormName, "dist", "Район/Нас.пункт");
	}
	em+= trf(strFormName, "levels", "Этажность дома"); 	
	em+= trf(strFormName, "levs","Этажи");
	em+= trf(strFormName, "strokalive", "Строка площадей");
	em+= trfn(strFormName, "numr", "Количество комнат"); 
	
	em+= testFloatValue(strFormName, "sall", "Общая площадь", 1); 	
	em+= testFloatValue(strFormName, "slive", "Жилая площадь", 0); 
	em+= testFloatValue(strFormName, "skuch", "Площадь кухни", 0); 
	em+= testFloatValue(strFormName, "skor", "Площадь прихожей", 0); 
	//em+= testFloatValue(strFormName, "pot", "Высота потолков", 1); 
	em+= testFloatValue(strFormName, "cenaedit", "Цена", 0); 
	em+= testFloatValue(strFormName, "cenaeditYE", "УЕ", 0);
		
	if ( document.forms[strFormName].elements['docType'] ) {
		intDocType = document.forms[strFormName].elements['docType'].value;
	}
	
	if ( ( intIsOperator == 1 ) && ( intDocType > 0 ) ) {
		// проверка валидности дат договора
		em+= tfp(strFormName, "dBegin", "дата начала договора", "^[0-9]{2}\\.{1}[0-9]{2}\\.{1}[0-9]{4}$", "поле \"ДАТА НАЧАЛА ДОГОВОРА\" долженно быть в формате \"дд.мм.гггг\";");
		em+= tfp(strFormName, "dEnd", "дата окончания договора", "^[0-9]{2}\\.{1}[0-9]{2}\\.{1}[0-9]{4}$", "поле \"ДАТА ОКОНЧАНИЯ ДОГОВОРА\" долженно быть в формате \"дд.мм.гггг\";");
	}
		
	if ( em == '') {
		boolResult = true;
		document.forms[strFormName].submit(); 		
	}
	else {
		alert(em);		
	}
	return boolResult;
}

/* обновляет поля на форме новостройки */
function updateFieldsByIdHouse(intIdHouse)
{
	var objSelectTypeHouse = document.getElementById('k_building_dom');
	if (jQuery) {		
		jQuery("#updFields").html('Запрос данных с сервера...');
		jQuery.getJSON('/ajax/gethouseinfo/' + intIdHouse + '.html', {params: "text"}, function(obj) { 
			document.getElementById('adres').value = obj.adres;
			document.getElementById('sadres').value = obj.sadres;
			document.getElementById('levels').value = obj.levels;
			document.getElementById('k_building_dom').selectedIndex = setSelection(document.getElementById('k_building_dom'), obj.k_building_dom);
			document.getElementById('kvdate_end').selectedIndex = setSelection(document.getElementById('kvdate_end'), obj.kvdate_end);			
			document.getElementById('selectStationHowGet').selectedIndex = setSelection(document.getElementById('selectStationHowGet'), obj.stationHowGet);
			updSearch(obj.reg, obj.dept, obj.dist, obj.street, obj.station);
		} );		
		jQuery('#updFields').html('');
	}
	else {
		alert('Не удалось получить данные с сервера! Заполните поля вручную!');
	}
}

/* функция строит окно с этажами */
function showSelectWindow(strSelected, strTextValues, fieldName, fieldResult, fieldCount, formName)
{
	var l = document.forms[formName].elements[fieldCount].value;
	if (document.forms[formName].elements[fieldResult].value!="") {
		strSelected=document.forms[formName].elements[fieldResult].value;
	}
	if (l=="")
	{
		alert("поле \"" + (fieldName.toUpperCase()) + "\" не заполнено;\n");
	}
	else {
		if (isNaN(l)) {
			var s = new Array();
			s=l.split("-");
			max_floor_ind=s.length-1;
			l=s[max_floor_ind];
			if (l>0) {
				openWindow('/spb/term/CheckBoxWindowFloors.php'+'?c='+l+'&r='+fieldResult+'&t='+strTextValues+'&s='+strSelected,200,400);
			}
			else {
				alert("поле \"" + (fieldName.toUpperCase()) + "\" должно быть числом;\n");
			}
		}
		else {
			if (l>0) {
				openWindow('/spb/term/CheckBoxWindowFloors.php'+'?c='+l+'&r='+fieldResult+'&t='+strTextValues+'&s='+strSelected,200,400);
			}
			else {
				alert("поле \"" + (fieldName.toUpperCase()) + "\" должно быть больше нуля;\n");
			}
		};
	};
}

/* функция проверяет форму загородной */
function testFormFarm(strFormName, intUpdateAddress, intIsOperator) {
	var em = "";
	var boolResult = false;
	var intDocType = 0;
		
	em+= tddlBulgakov(strFormName, "agentID","Агент"); 
	if ( intUpdateAddress == 1 ) {
		em+= tddl2(strFormName, "reg", "Регион"); 
		em+= tddl2(strFormName, "dept", "Адм.центр"); 
		em+= tddl2(strFormName, "dist", "Район/Населенный пункт"); 
	}
	
	em+= tddlBulgakov(strFormName, "zTypeObject", "Объект"); 
	em+= tddlBulgakov(strFormName, "zUrStatus", "Юр.статус");
	
	em+= testFloatValue(strFormName, "zSAll", "Общая площадь", 0); 
	em+= trfn(strFormName, "zPrice", "Цена"); 
	em+= tnf(strFormName, "zFloors", "этажей"); 
	em+= tnf(strFormName, "zSizeX", "размер - X"); 
	em+= tnf(strFormName, "zSizeY", "размер - Y"); 	
	em+= tnf(strFormName, "zAmountRooms", "Количество комнат"); 
	em+= testFloatValue(strFormName, "zSLife", "Жилая площадь", 0); 
	em+= testFloatValue(strFormName, "zSKitchen", "Площадь кухни", 0); 
	em+= tnf(strFormName, "zYear", "Год"); 
	em+= trfn(strFormName, "zLand10x10", "Площадь участка"); 
	em+= tnf(strFormName, "zRemoteness", "Удаленность от жд станции");
		
	if ( document.forms[strFormName].elements['docType'] ) {
		intDocType = document.forms[strFormName].elements['docType'].value;
	}
	
	if ( ( intIsOperator == 1 ) && ( intDocType > 0 ) ) {
		// проверка валидности дат договора
		em+= tfp(strFormName, "dBegin", "дата начала договора", "^[0-9]{2}\\.{1}[0-9]{2}\\.{1}[0-9]{4}$", "поле \"ДАТА НАЧАЛА ДОГОВОРА\" долженно быть в формате \"дд.мм.гггг\";");
		em+= tfp(strFormName, "dEnd", "дата окончания договора", "^[0-9]{2}\\.{1}[0-9]{2}\\.{1}[0-9]{4}$", "поле \"ДАТА ОКОНЧАНИЯ ДОГОВОРА\" долженно быть в формате \"дд.мм.гггг\";");
	}
		
	if ( em == '') {
		boolResult = true;
		document.forms[strFormName].submit(); 		
	}
	else {
		alert(em);		
	}
	return boolResult;
}

/* получение таблицы статистики */
function getStatTable(strIdDiv, strUrl)
{
	if (jQuery) {		
		jQuery("#" + strIdDiv).html('Запрос данных с сервера...');
		jQuery.post(strUrl, {}, function(data) { jQuery('#' + strIdDiv).html(data); } );		
	}
	else {
		alert('Не удалось получить данные с сервера!');
	}
}


/* функция показывает форму коментирования в терминале */
function commentFormShow(intIdObject, intIdBase, strDivName, strRefresh)
{
	if (jQuery) {
		jQuery("#" + strDivName).html('секундочку...');
		jQuery.get('/ajax/getformcomment/' + intIdObject + '.html?query=base/' + intIdBase + '/refresh/' + strRefresh, {}, function(data) { jQuery("#" + strDivName).html(data); } );		
	}
	else {
		errorNoSupportJQuery();
	}
	return true;
}

/* функция прячет форму коментирования в терминале */
function commentFormHide(strDivName)
{
	if (jQuery) {
		jQuery("#" + strDivName).html('');
	}
	else {
		errorNoSupportJQuery();
	}
	return true;
}

/* функция проверяет и добавляет комментарий */
function commentAdd(intIdObject, intIdBase, strDivName, strTextareaName)
{	
	if (jQuery) {
		var strText = jQuery('#' + strTextareaName).val();
		if ( strText == '' ) {
			alert('Введите текст!');
		}
		else {
			jQuery.post('/ajax/addcomment/' + intIdObject + '.html?query=base/' + intIdBase, {commentText: strText}, function(data) { jQuery("#" + strDivName).html(data); } );	
		}
	}
	else {
		errorNoSupportJQuery();
	}
}

/* ошибка загрузки jQuery */
function errorNoSupportJQuery()
{
	alert('Извините, не загружена библиотека jQuery');
}