// codepage: utf-8

function SelectObj(obj) {
	obj.focus();
	obj.selectionStart = 0;
	obj.selectionEnd = 20;
}

function empty( str ) {

    if (str.length == 0) { return true; }
    else { return false}

}

function NameIsCorrect ( user_name ) {
result = false;

	if (!empty(user_name)) result = true;

return result;
}

function ShowNumber( number ) {
result = '';
digit = 3;

	number = number.toString();
	l = number.length;
	j = 0;
	for ( i = l; i > 0; i-- ) {
		result = number[i - 1] + result;
		j++;
		if ( j == 3 ) {
			result = ' ' + result;
			j = 0;
		}
	}

return result;
}

function UserPriceAverPrice() {

	c = 0;
	averprice = 0;
	for ( i = 1; i < 6; i++) {
		price = ($('user_url_'+i+'_price').value)
		price = price.replace(/\s/g, "")
		if (empty(price)) continue;

		price = parseInt(price)
		c++;
		averprice += price;
	}
	if (!empty(c)) averprice = intval( averprice / c );
	
	if (!empty(averprice)) {
		$('user_url_aver_price').value = '';
		$('user_url_aver_price').value = averprice;
		$('user_url_aver_price').style.background = '#F1F1F1';
	}
	
}

function UserPriceCheckUrl( id ) {
	//url = ($('user_url_'+id+'_link').value)
	//url = url.replace(/\s/g, "")
	////if (url.length < 1) return false;
	//if (!empty(url)) {
	//	$('user_url_'+id+'_price').readOnly = false;
	//	$('user_url_'+id+'_price').style.background = '#FFFFFF';
	//} else {
	//	$('user_url_'+id+'_price').readOnly = 'readonly';
	//	$('user_url_'+id+'_price').style.background = '#C1C1C1';
	//}
}

//function SendUserPrice ( keystring, user_object_id, user_name, user_phone_prefix, user_phone, user_has_seen_car, user_price, object_price, object_price_min ) {
function SendUserPrice ( chapter, user_object_id, object_price, object_price_min ) {

	user_name = $('user_name').value;
	user_phone_prefix = $('user_phone_prefix').value;
	user_phone = $('user_phone').value;
	user_mail = $('user_mail').value;
	user_price = $('user_price').value;
	user_message = $('user_message').value;

	user_price = user_price.replace(/\s/g, "")
//	user_price = parseInt(user_price)
	if (object_price_min) {
		object_price_min = parseInt(object_price_min)
	} else { object_price_min = object_price / 2}
	object_price = parseInt(object_price)

	//for ( i = 1; i < 6; i++) {
	//	eval ( "user_url_"+i+"_link = $('user_url_1_link').value" );
	//	eval ( "user_url_"+i+"_price = $('user_url_1_price').value" );
	//	alert(eval("user_url_"+i+"_link"))
	//}


	$('FormUserPriceBlockError').innerHTML = '<span class="red">';
	flag_error = false;
	$('user_name').style.background = '#FFFFFF';
	if (NameIsCorrect($('user_name').value) == false) {
		flag_error = true;
		$('FormUserPriceBlockError').innerHTML += 'Вы забыли представиться.<br />';
		$('user_name').style.background = '#FF9999';
		SelectObj($('user_name'));
	}

	tmp_user_phone = $('user_phone_prefix').value + $('user_phone').value;3
	$('user_phone_prefix').style.background = '#FFFFFF';
	$('user_phone').style.background = '#FFFFFF';
	if (tmp_user_phone.length < 7) {
		$('FormUserPriceBlockError').innerHTML += 'Неправильно указан номер телефона.<br />';
		$('user_phone_prefix').style.background = '#FF9999';
		$('user_phone').style.background = '#FF9999';
		if (!flag_error) {
			SelectObj($('user_phone_prefix'));
			flag_error = true;
		}
	}

	$('user_price').style.background = '#FFFFFF';
	
	if ( empty(user_price) ) {
		$('FormUserPriceBlockError').innerHTML += 'Укажите цену, по которой готовы приобрести данный объект.<br />';
		$('user_price').style.background = '#FF9999';
		if (!flag_error) {
			SelectObj($('user_price'));
			flag_error = true;
		}
	} else {
//		alert( object_price_min + ' ' + object_price + ' ' + user_price )
		if ( ((user_price < object_price_min ) && (object_price_min != 0)) || ((user_price > object_price) && (object_price != 0)) ) {
			if (user_price < object_price_min ) str_price = 'низкая';
			if (user_price > object_price) str_price = 'высокая';
			$('FormUserPriceBlockError').innerHTML += 'Ваша цена слишком ' + str_price + '. Попробуйте предложить другую.<br />' + 'Цена должна быть от ' + ShowNumber( object_price_min ) + ' до ' + ShowNumber( object_price ) + ' рублей.<br />';
	//		$('FormUserPriceBlockError').innerHTML += 'Ваша цена слишком ' + str_price + '. Попробуйте предложить другую.<br />';
			$('user_price').style.background = '#FF9999';
			if (!flag_error) {
				SelectObj($('user_price'));
				flag_error = true;
			}
		}
	}
	
	if (user_message == 'Считаю мою цену обоснованной, т.к. ...') user_message = '';

	$('FormUserPriceBlockError').innerHTML += '</span>';

	if (flag_error) return;

    //формируем строку с параметрами запроса
//    var pars = $H({user_captcha:keystring}).toQueryString()+'&'+$H({user_object_id:user_object_id}).toQueryString()+'&'+$H({user_name:user_name}).toQueryString()+'&'+$H({user_phone_prefix:user_phone_prefix}).toQueryString()+'&'+$H({user_phone:user_phone}).toQueryString()+'&'+$H({user_has_seen_car:user_has_seen_car}).toQueryString()+'&'+$H({user_price:user_price}).toQueryString();

    var pars  = $H({chapter:chapter}).toQueryString()+'&'+$H({user_object_id:user_object_id}).toQueryString();
    pars += '&'+$H({user_name:user_name}).toQueryString();
    pars += '&'+$H({user_phone_prefix:user_phone_prefix}).toQueryString();
    pars += '&'+$H({user_phone:user_phone}).toQueryString();
    pars += '&'+$H({user_mail:user_mail}).toQueryString();
    pars += '&'+$H({user_price:user_price}).toQueryString();
    pars += '&'+$H({user_message:user_message}).toQueryString();
    
    pars += '&' + $H({user_url_1_link:$('user_url_1_link').value}).toQueryString();
    pars += '&' + $H({user_url_1_price:$('user_url_1_price').value}).toQueryString();
    pars += '&' + $H({user_url_2_link:$('user_url_2_link').value}).toQueryString();
    pars += '&' + $H({user_url_2_price:$('user_url_2_price').value}).toQueryString();
    pars += '&' + $H({user_url_3_link:$('user_url_3_link').value}).toQueryString();
    pars += '&' + $H({user_url_3_price:$('user_url_3_price').value}).toQueryString();
    pars += '&' + $H({user_url_4_link:$('user_url_4_link').value}).toQueryString();
    pars += '&' + $H({user_url_4_price:$('user_url_4_price').value}).toQueryString();
    pars += '&' + $H({user_url_5_link:$('user_url_5_link').value}).toQueryString();
    pars += '&' + $H({user_url_5_price:$('user_url_5_price').value}).toQueryString();
    
//alert(pars)

	new Ajax.Request (
	    root_dir+"js/php/check_userprice.php",
	    {   method:"post", parameters:pars,
		onSuccess : AfterSendUserPrice
	    }
	)

}

function AfterSendUserPrice(transport) {
	var result = eval('(' + transport.responseText + ')');
	if ( result != 1) {
		alert ( 'Возникла ошибка. Попробуйте повторить позже.' )
	}
	else {
		$('BlockUserPrice').innerHTML = '<center>Спасибо! Мы рассмотрим Ваше предложение. <br><br>Обращаем внимание, что Ваше предложение носит информационный характер и не является публичной офертой в соответствии с п. 2 ст.437 Гражданского кодекса Российской Федерации.</center>';
	}
}

