Array.prototype.remove = function () {
    var ind;
    for(var i=0; i<arguments.length; i++) {
       if((ind = this.indexOf(arguments[i])) > -1) this.splice(ind, 1);
    }
};
String.prototype.filterFloat = function() {
	var v = this.toString();
	return (v==='' ? '' : String(Math.abs(parseFloat(v)).toFixed(1)));
};
String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g,"");
};

Ext.isDate = function(){
	return false;
}

function bookmark (url, title) {
	if (window.sidebar) { // Mozilla Firefox Bookmark
		window.sidebar.addPanel(title, url,"");
	} else if( window.external ) { // IE Favorite
		window.external.AddFavorite( url, title);
	}else if(window.opera && window.print){ // Opera Hotlist
		return true;
	}
}

function checkAddPhotoForm() {

	return true;
}

function selectPhotoCategory(el) {
	if (el.value.trim() != '') {
		cat_id = el.value.trim();
		window.location = '/photogallery/userarea/albums/search/cat_id=' + cat_id + '/';
	} else window.location = '/photogallery/userarea/albums/';
}

function makePhotoAsBase(id, album_id) {
	if (id > 0 && album_id > 0) {
		Ext.Ajax.request({
			url: '/ajax/auto/photogallery_select_base_photo.php',
			headers: {},
			callback: function (options, success, response) {
				var res = Ext.decode(response.responseText);
				if (res.success == true){
					goTo(window.location.href);
				}
				else if (res.message != '') {
					alert(res.message);
				}
			},
			params: {
				photo_id: id,
				album_id: album_id
			}
		});
	}
}

function removeGalleryPhoto(id) {
	if (id > 0) {
		Ext.Ajax.request({
			url: '/ajax/auto/photogallery_remove_photo.php',
			headers: {},
			callback: function (options, success, response) {
				var res = Ext.decode(response.responseText);
				if (res.success == true){
					goTo(window.location.href);
				}
				else if (res.message != '') {
					alert(res.message);
				}
			},
			params: {
				photo_id: id
			}
		});
	}
}

function removeAlbum(id) {
	
	if(confirm('Вы уверены что хотите удалить альбом?')) {
	
		if (id != 0) {
			Ext.Ajax.request({
				url: '/ajax/auto/photogallery_remove_album.php',
				headers: {},
				callback: function (options, success, response) {
					var res = Ext.decode(response.responseText);
					if (res.success == true){
						goTo(window.location.href);
					}
					else if (res.message != '') {
						alert(res.message);
					}
				},
				params: {
					cat_id: id
				}
			});
		}
	}
	
	return false;
}

function createAlbum() {
	var category = Ext.get('photoCategories');
	var uname = Ext.get('album_name');
	var description = Ext.get('album_description');
	var dontSend = false;

	if (category.dom.value.trim() == '') {
		markFieldInvalid(category.dom);
		dontSend = true;
	}
	if (uname.dom.value.trim() == '') {
		markFieldInvalid(uname.dom);
		dontSend = true;
	}
	// Show errors
	if (dontSend) {
		alert('Заполните обязательные поля!');
		return false;
	}

	Ext.Ajax.request({
		url: Ext.get('add_album_form').dom.action,
		headers: {},
		callback: function (options, success, response) {
			var res = Ext.decode(response.responseText);
			if (res.success == true){
				goTo(res.url_goto);
			}
			else alert('Ошибка при сохранении альбома');
		},
		params: {
			uname: uname.dom.value.trim(),
			description: description.dom.value.trim(),
			category: category.dom.value.trim(),
			action: 'add'
		}
	});
	return false;
}

function editAlbum() {
	var category = Ext.get('photoCategories');
	var uname = Ext.get('album_name');
	var description = Ext.get('album_description');
	var album_id = Ext.get('album_id');
	var dontSend = false;

	if (category.dom.value.trim() == '') {
		markFieldInvalid(category.dom);
		dontSend = true;
	}
	if (uname.dom.value.trim() == '') {
		markFieldInvalid(uname.dom);
		dontSend = true;
	}
	// Show errors
	if (dontSend) {
		alert('Заполните обязательные поля!');
		return false;
	}

	Ext.Ajax.request({
		url: Ext.get('edit_album_form').dom.action,
		headers: {},
		callback: function (options, success, response) {
			var res = Ext.decode(response.responseText);
			if (res.success == true){
				goTo(res.url_goto);
			}
			else alert('Ошибка при сохранении альбома');
		},
		params: {
			uname: uname.dom.value.trim(),
			description: description.dom.value.trim(),
			category: category.dom.value.trim(),
			album_id: album_id.dom.value,
			action: 'edit'
		}
	});
	return false;
}

function editPhoto(id) {
	var uname = Ext.get('photo_title');
	var description = Ext.get('photo_desc');
	var tags = Ext.get('photo_tags');
	var dontSend = false;

	if (uname.dom.value.trim() == '') {
		markFieldInvalid(uname.dom);
		dontSend = true;
	}
	// Show errors
	if (dontSend) {
		alert('Заполните обязательные поля!');
		return false;
	}

	Ext.Ajax.request({
		url: '/ajax/auto/photogallery_edit_photo.php',
		headers: {},
		callback: function (options, success, response) {
			var res = Ext.decode(response.responseText);
			if (res.success == true){
				goTo(res.url_goto);
			}
			else alert('Ошибка при сохранении альбома');
		},
		params: {
			photo_id: id,
			uname: uname.dom.value.trim(),
			description: description.dom.value.trim(),
			tags: tags.dom.value.trim()
		}
	});
	return false;
}

function addPhoto(id) {
	var uname = Ext.get('photo_title');
	var description = Ext.get('photo_desc');
	var tags = Ext.get('photo_tags');
	var dontSend = false;

	if (uname.dom.value.trim() == '') {
		markFieldInvalid(uname.dom);
		dontSend = true;
	}

	var form = Ext.get('add_photo_form').dom;

	var photos = form.getElementsByTagName('input');

	var isPhotosSelected = false;

	for(var i=0; i<photos.length; i++) {
		if(photos[i].getAttribute('type') == 'file') {
			if(photos[i].getAttribute('name') == 'photo[]') {
				isPhotosSelected |= (photos[i].value != '');
			}
		}
	}

	if (!isPhotosSelected) {
		for(var i=0; i<photos.length; i++) {
			if(photos[i].getAttribute('type') == 'file') {
				if(photos[i].getAttribute('name') == 'photo[]') {
					markFieldInvalid(photos[i]);
				}
			}
		}
		dontSend = true;
	}

	// Show errors
	if (dontSend) {
		alert('Заполните обязательные поля!');
		return false;
	}

	Ext.get('add_photo_form').dom.submit();

	// callback: addPhotoCallback
}

function addPhotoCallback(responseText) {
	var res = Ext.decode(responseText);

	if (res.success == true){
		goTo(res.url_goto);
	}
	else {
		alert(res.message);
	}
}

// login
function sendLoginForm() {
	var uname = Ext.get('login');
	var passwd = Ext.get('password');
	var saveme = ((Ext.get('saveme').dom.checked == true) ? 1 : 0);

	Ext.Ajax.request({
		url: '/controllers/login.php',
		success: successLogin,
		failure: failureAlert,
		headers: {},
		params: {
			loginUsername: uname.dom.value.trim(),
			loginPassword:passwd.dom.value,
			loginRemember:saveme
		}
	});
}

function sendPassportForm() {
	var uname = Ext.get('username');
	var passwd = Ext.get('password');
	var rememberMe = ((Ext.get('rememberMe').dom.checked == true) ? 1 : 0);
	if ($('site_cookie_path')) {
		var pathCookie = $('site_cookie_path').value;
	} else {
		var pathCookie = false;
	}
	if (rememberMe) setCookie2('remember', 1, 0, '/', pathCookie);
	if (!getCookie2('returnPath')) setCookie2('returnPath', window.location.href, 0, '/', pathCookie);
	Ext.Ajax.request({
		url: '/ajax/passport_login.php',
		headers: {},
		params: {
			loginUsername: uname.dom.value.trim(),
			loginPassword: passwd.dom.value,
			loginRemember: rememberMe
		}
	});
	setCookie2('favorites', ',', 0, '/', pathCookie)
	return true;
}

function successLogin(response, options) {
	var res = Ext.decode(response.responseText);
	if(res.success==true){
		if(Ext.get('return') && Ext.get('return').dom.value!=''){
			var redirect_url = Ext.get('return').dom.value;
		}else{
			var redirect_url = '/myadverts/';
		}

		if (redirect_url.match('search')){
			Ext.Ajax.request({
				url: '/ajax/save_search_alert.php',
				callback: function (options, success, response) {
						var res = Ext.decode(response.responseText);
						if (res.success==true && res.url_goto){
							goTo(res.url_goto);
						}
						else if (res.success==true){
							goTo('/myadverts/alerts/');
						}
						else alert('Ошибка при сохранении подписки');
					},
				params: {url:redirect_url}
			});
		}


		if(res.usertype == 'pseller' && redirect_url == '/myadverts/') {
			goTo('/psellerAdverts/');
		} else {
			if(Ext.get('domain') && Ext.get('domain').dom.value!=''){
				goTo('http://'+Ext.get('domain').dom.value+'.'+window.location.hostname+redirect_url);
			}else
			goTo(redirect_url);
		}
	}else if (res.errors.reason){
		var erm = Ext.get('error');
		if (erm){
			erm.query('li/h4')[0].innerHTML=res.errors.reason;
			erm.dom.style.display="block";
		}
	}else{
		var erm = Ext.get('error');
		if (erm) erm.dom.style.display="block";
	}

}
// end login


// register & restore password
function sendRegisterForm(btn) {
	var oldValue = btn.value;
	btn.value = 'Ждите...';
	btn.disabled = true;
	Ext.get(btn).parent('div').replaceClass('btn-a', 'btn-b');

	hideAllErrorMessages();

	errors = false;
	agreement = document.getElementById('agreement');
	if(agreement.checked == false) {
		document.getElementById('agreement_error_message').style.display = 'block';
		errors = true;
	}

	document.getElementById('email').value = document.getElementById('email').value.trim();
	email = document.getElementById('email');
	if(email.value.length == 0) {
		document.getElementById('empty_email_error_message').style.display = 'block';
		errors = true;
	}

	password = document.getElementById('password');
	if(password.value.length == 0) {
		document.getElementById('empty_password_error_message').style.display = 'block';
		errors = true;
	}

	passwordConfirm = document.getElementById('passwordConfirm');
	if(passwordConfirm.value.length == 0) {
		document.getElementById('empty_confirm_password_error_message').style.display = 'block';
		errors = true;
	}

	captcha = document.getElementById('captcha-edit');
	if(captcha.value.length == 0) {
		document.getElementById('empty_captcha_error_message').style.display = 'block';
		errors = true;
	}

	var tmp, errors2 = false;

	tmp = $('first_name');
	if(tmp.value!='' && !isText(tmp.value)) { onkp(tmp); errors2 = true; }

	tmp = $('last_name');
	if(tmp.value!='' && !isExText(tmp.value)) { onkp(tmp); errors2 = true; }

	tmp = $('phone');
	if(tmp.value!='' && !isPhone(tmp.value)) { onkp(tmp); errors2 = true; }

	tmp = $('mobile_phone');
	if(tmp.value!='' && !isPhone(tmp.value)) { onkp(tmp); errors2 = true; }

	tmp = $('icq');
	if(tmp.value!='' && !isDigit(tmp.value)) { onkp(tmp); errors2 = true; }

	if(errors2 && !errors){
		btn.value = 'Зарегистрироваться';
		btn.disabled = false;
		Ext.get(btn).parent('div').replaceClass('btn-b', 'btn-a');
		return false;
	}

	if(errors) {
		document.getElementById('errors_panel').style.display = 'block';
		btn.value = 'Зарегистрироваться';
		btn.disabled = false;
		Ext.get(btn).parent('div').replaceClass('btn-b', 'btn-a');
		return false;
	}

	Ext.Ajax.request({
		form: 'registerForm',
		success: function(response, options){successRegister(response,options, btn);},
		failure:  function(response, options){
			document.getElementById('errors_panel').style.display = 'block';
			btn.value = 'Зарегистрироваться';
			btn.disabled = false;
			Ext.get(btn).parent('div').replaceClass('btn-b', 'btn-a');
			failureAlert(response,options, btn);
		},
		params: {action: 'register'}
	});

	return false;
}

function checkUserExists() {
	email = Ext.get('email').dom.value;

	Ext.Ajax.request({
		url: '/ajax/register.php',
		success: successUserExists,
		failure: function(){},
		params: {f_email: email,
		action: 'check_user_exists'}
	});
}

function successRegister(response, options, btn) {

	hideAllErrorMessages();
	var res = Ext.decode(response.responseText);
	if(res.success==true){
		config = $('config').value;
		if (config == 1) {
			$('login_username').value = $('email').value;
			$('login_password').value = $('password').value;
			$('passportForm').submit();
		} else {
		// auth
		uname = Ext.get('email');
		passwd = Ext.get('password');
		Ext.Ajax.request({
			url: '/controllers/login.php',
			success: successLogin,
			failure: failureAlert,
			headers: {},
			params: {
				loginUsername: uname.dom.value,
				loginPassword: passwd.dom.value
			}
		});
		}
	}else{
		btn.value = 'Зарегистрироваться';
		btn.disabled = false;
		Ext.get(btn).parent('div').replaceClass('btn-b', 'btn-a');
		showRegisterErrors(res.errors);
	}
	return false;
}

function onkp(f) {
	tmp = $(f);
	if(tmp) tmp.onkeypress();
}

function showRegisterErrors(errors) { //TODO: написать нормально функцию
	var tmp=false;
	for(i=0; i<errors.length; i++) {

		if(errors[i]['exvalid']) { onkp(errors[i]['field']); continue; }
		tmp = true;

		key = errors[i]['type'] + '_error_message';
		if ($(key)) $(key).style.display = 'block';

		key = errors[i]['field'] + '_error_icon';
		if ($(key)) $(key).style.display = 'inline';

		key = errors[i]['field'];

		$(key).className = 'field_error';
	}
	if (tmp && $('errors_panel')) $('errors_panel').style.display = 'block';
}

function successUserExists(response, options) {
	var res = Ext.decode(response.responseText);
	if(res.success==false){
		hideAllErrorMessages();
		showRegisterErrors(res.errors);
	} else {
		document.getElementById('user_unique_error_message').style.display = 'none';
		hidePanelIfEmpty();
	}
	return false;
}

function failureAlert() {
	document.getElementById('alerts').style.display = 'block';
	document.getElementById('ajax_error_alert').style.display = 'block';

	return false;
}

function hideAllErrorMessages()
{
	document.getElementById('errors_panel').style.display = 'none';

	box = document.getElementById('errors_panel');
	for(i=0; i<box.childNodes.length; i++) {
		if(box.childNodes[i].id) {
			box.childNodes[i].style.display = "none";
		}
	}

	error_icons = Ext.query('div[class="error_icon"]');
	for(i=0; i<error_icons.length; i++) {
		if(error_icons[i].id) {
			error_icons[i].style.display = "none";
		}
	}
}

function hidePanelIfEmpty(){

	is_empty = true;

	panel = document.getElementById('errors_panel');
	for(i=0; i<panel.childNodes.length; i++) {
		if(typeof(panel.childNodes[i].style) != 'undefined' && panel.childNodes[i].style.display != 'none') {
			is_empty = false;
		}
	}

	if(is_empty) {
		document.getElementById('errors_panel').style.display = 'none';
	}
}

function isEmail(v) {
	//	var reg = /^([A-Z]+@([^@\.]{2,}\.)+[^@\.]{2,})?$/i;
	var reg = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
	return reg.test(v);
}
function isText(v) {
	var reg = /^([a-zа-яё])+$/i;
	return reg.test(v);
}
function isDigit(v) {
	var reg = /^([0-9])+$/i;
	return reg.test(v);
}
function isPhone(v) {
	var reg = /^([0-9\-\(\)\+])+$/i;
	return reg.test(v);
}
function isICQ(v) {
	var reg = /^([0-9\-])+$/i;
	return reg.test(v);
}
function isURL(v) {
	var reg = /^([^\s])+$/i;
	return reg.test(v);
}
function isExText(v) {
	var reg = /^([a-zа-яё\-\'\`])+$/i;
	return reg.test(v);
}

function isExTextDigit(v) {
	var reg = /^([a-zа-яё\-\'\`0-9 ])+$/i;
	return reg.test(v);
}

function validateEmail(){
	email = Ext.get('email');
	email = email.dom;
	if(!isEmail(email.value)) {
		email.className = 'field_error';
		document.getElementById('email_error_icon').style.display = 'inline';
	} else {
		email.className = '';
		icon = document.getElementById('email_error_icon').style.display = 'none';
	}
}

function validateLogin(){
	email = Ext.get('login');
	email = email.dom;
	if(!isEmail(email.value)) {
		email.className = 'field_error';
		document.getElementById('email_error_icon').style.display = 'inline';
	} else {
		email.className = '';
		icon = document.getElementById('email_error_icon').style.display = 'none';
	}
}

function validateLoginPassword(){
	var password = document.getElementById('password');
	var password_length = document.getElementById('password_length').innerHTML;
	if(password.value.length < password_length) {
		password.className = 'field_error';
		document.getElementById('password_error_icon').style.display = 'inline';
	} else {
		password.className = '';
		document.getElementById('password_error_icon').style.display = 'none';
	}
}

function validatePassword(){
	var password = document.getElementById('password');
	var password_length = document.getElementById('password_length').innerHTML;
	if(password.value.length < password_length) {
		password.className = 'field_error';
		document.getElementById('password_error_icon').style.display = 'inline';
	} else {
		password.className = '';
		document.getElementById('password_error_icon').style.display = 'none';

		checkConfirmPassword();
	}
}

function checkConfirmPassword() {
	var password = Ext.get('password').dom;
	var confirm = Ext.get('passwordConfirm').dom;
	if(password.value !=  confirm.value) {
		confirm.className = 'field_error';

		document.getElementById('passwordConfirm_error_icon').style.display = 'inline';
	} else {
		confirm.className = '';

		document.getElementById('passwordConfirm_error_icon').style.display = 'none';
	}
}

function switchDisplayRegisterAdditionalInfo() {
	block = Ext.get('additional_info');
	block.enableDisplayMode();

	if(block.isDisplayed()) {
		block.hide();
	} else {
		block.show();
	}
}

function goToRestore(){
	var path = '/login/restore/';
	var email = $('login').value;
	if(email) {
		path = path + '?email=' + email;
	}

	window.location = path;
}

function goToRestorePassport(){
	var path = '/login/restore/';
	var email = $('username').value;
	if(email) {
		path = path + '?email=' + email;
	}
	window.location = path;
}

function setDefaultEmailToRestoreField() {
	email =	getValueFromURL('email', document.location.toString());
	if(email){
		$('email').value = email;
	}
}

function sendRestorePasswordForm(btn) {
	var oldValue = btn.value;
	btn.value = 'Ждите...';
	btn.disabled = true;
	Ext.get(btn).parent('div').replaceClass('btn-a', 'btn-b');

	document.getElementById('errors_panel').style.display = 'none';
	document.getElementById('message_panel').style.display = 'none';
	document.getElementById('alerts').style.display = 'none';

	Ext.Ajax.request({
		form: 'resorePasswordForm',
		success: function (response, options) {
			btn.value = oldValue;
			btn.disabled = false;
			Ext.get(btn).parent('div').replaceClass('btn-b', 'btn-a');

			successRestorePassword(response, options);
		},
		failure: function () {
			btn.value = oldValue;
			btn.disabled = false;
			Ext.get(btn).parent('div').replaceClass('btn-b', 'btn-a');

			failureAlert();
		},
		params: {action: 'restore'}
	});
	return false;
}

function activatePassword() {
	var input_key  = getValueFromURL('key', document.location.toString());

	if(input_key !== false){
		Ext.Ajax.request({
			url: '/ajax/restorePassword.php',
			success: successActivatePassword,
			failure: failureAlert,
			params: {key: input_key,
			action: 'activate'}
		});
	}
}

function successActivatePassword(response, options) {
	var res = Ext.decode(response.responseText);
	if(res.success){
		$('activate_password_success').style.display = 'block';
		$('message_panel').style.display = 'block';
	} else {
		hideAllErrorMessages();
		document.getElementById('message_panel').style.display = 'none';
		errors = res.errors;
		for(i=0; i<errors.length; i++) {
			key = errors[i]['type'] + '_error_message';
			$(key).style.display = 'block';
		}
		$('errors_panel').style.display = 'block';
	}
}


function successRestorePassword(response, options) {

	var res = Ext.decode(response.responseText);
	if(res.success){
		if (res.errors && res.errors[0]['type'] == 'get_secret_answer') {
			var secretQuestion = '<b>' + res.errors[0].field + '</b>';
			document.getElementById('secretQuestion').innerHTML = secretQuestion;
			document.getElementById('secretBlock').style.display = 'block';
			document.getElementById('getsecretanswer').value = 0;
		} else {
			document.getElementById('secretBlock').style.display = 'none';
			document.getElementById('message_panel').style.display = 'block';
			document.getElementById('restore_block').style.display = 'none';
		}
	} else {
		document.getElementById('message_panel').style.display = 'none';
		var errors = res.errors;
		if (errors && errors[0]['type'] == 'get_secret_answer') {
			var secretQuestion = '<b>' + errors[0].field + '</b>';
			document.getElementById('secretQuestion').innerHTML = secretQuestion;
			document.getElementById('secretBlock').style.display = 'block';
			document.getElementById('secretanswer').value = '';
			document.getElementById('getsecretanswer').value = 0;
			document.getElementById('error_restore_error_message').style.display = 'block';
			document.getElementById('restore_errors_panel').style.display = 'block';
		} else {
			for(i=0; i<errors.length; i++) {
				key = errors[i]['type'] + '_error_message';
				document.getElementById(key).style.display = 'block';
			}
			document.getElementById('errors_panel').style.display = 'block';
		}
	}
	return false;
}
// end register & restore password

// send message to ad's author
function sendMes2AuthorForm(id, btn) {
	var oldValue = btn.value;
	btn.value = 'Ждите...';
	btn.disabled = true;
	Ext.get(btn).parent('div').replaceClass('btn-a', 'btn-b');

	Ext.Ajax.request({
		form: 'mes2authorForm',
		success: function(response, options){ successMes2AuthorForm(response, options, btn); },
		failure: function(response, options){ failureMes2AuthorForm(response, options, btn); },
		params: {action: 'mes2author', 'ad_id': id}
	});
	return false;
}
function successMes2AuthorForm(response, options, btn) {
	//reloadCaptha('mes2author_captcha', 'ad_id');

	btn.value = 'Отправить';
	btn.disabled = false;
	Ext.get(btn).parent('div').replaceClass('btn-b', 'btn-a');

	var res = Ext.decode(response.responseText);
	if(res.success==true){
		alert('Сообщение отправлено');
		hideIconErrs('mes2authorForm');
		showhide('author','show');
		window.userInfoLoaded=false;
	}else{
		showIconErrs(res.errors, 'mes2au_');
		alert('Заполните верно форму');
	}
}
function failureMes2AuthorForm(response, options, btn) {
	//reloadCaptha('mes2author_captcha', 'ad_id');
	btn.value = 'Отправить';
	btn.disabled = false;
	Ext.get(btn).parent('div').replaceClass('btn-b', 'btn-a');

	alert('Ошибка связи. Попробуйте повторить действие через несколько минут.');
}
function reloadCaptha(img, id, uni) {
	var ad_id = Ext.get(id).getValue();
	if(!uni) uni='';
	Ext.get(img).dom.src='/kcaptcha/index.php?id='+uni+ad_id+'&rand='+Math.random();
}
function clrForm(f) {
	var m = Ext.query('#'+f+' .inp');
	for(var i=0; i<m.length; i++) {
		m[i].firstChild.value = '';
	}
}
function hideIconErrs(idcont) {
	var m = Ext.query('#'+idcont+' .error_icon');
	for(var i=0; i<m.length; i++) hideFieldErr(Ext.get(m[i]).prev());
	clrForm(idcont);
}
function hideFieldErr(inp) {
	inp.parent().removeClass('error_label');
	if (inp.next()) {
		inp.next().dom.style.display = 'none';
	}
}
function showFieldErr(inp) {
	inp.parent().addClass('error_label');
	if (inp.next()) {
		inp.next().dom.style.display = 'inline';
	}
}
function showIconErrs(err, prefix) {
	for(i=0; i<err.length; i++) {
		showFieldErr(Ext.get(prefix + err[i]['field']).prev());
	}
}
function checkfield(el, v) {
	v = v.split('|');
	el = Ext.get(el);
	var er = false, tmp;
	for(i=0;i<v.length;i++) {
		tmp = el.getValue();
		if(v[i]=='empty' && tmp=='') { er = true; break; }
		if(v[i]=='email' && tmp!='' && !isEmail(tmp)) { er = true; break; }
		if(v[i]=='text' && tmp!='' && !isText(tmp)) { er = true; break; }
		if(v[i]=='extext' && tmp!='' && !isExText(tmp)) { er = true; break; }
		if(v[i]=='digit' && tmp!='' && !isDigit(tmp)) { er = true; break; }
		if(v[i]=='phone' && tmp!='' && !isPhone(tmp)) { er = true; break; }
		if(v[i]=='url' && tmp!='' && !isURL(tmp)) { er = true; break; }
		if(v[i]=='ICQ' && tmp!='' && !isICQ(tmp)) { er = true; break; }
		if(v[i]=='extextDigit' && tmp!='' && !isExTextDigit(tmp)) { er = true; break; }
	}
	if(er) showFieldErr(el);
	else hideFieldErr(el);
}
function checkfieldT(inp, v) {
	setTimeout(function(el){ return function() { checkfield(el, v); }; }(inp), 100);
}
// end send message to ad's author

// incorrect ad message
function sendIncorrectAdForm(formId, divId) {
  	Ext.Ajax.request({
		form: formId || 'incorrectadForm',
		success: function (response, options) {
	  		var res = Ext.decode(response.responseText);
	  		if (res.success == true) {
	  			alert('Сообщение отправлено');
	  			showhide(divId || 'warning', 'form');
	  		} else {
	  			alert(res.mes);
	  		}
	  		if ($('incorrect_button')) {
	  			$('incorrect_button').disabled = false;
	  			$('incorrect_button').value = 'Отправить';
	  		}
	  	},
		failure: function failureIncorrectAdForm() {
	  		alert(':(');
	  	}
	});

	return false;
}

function hideComment(el){
	var classEl = Ext.get(el).parent('dd').dom.className;
	if (classEl=='') Ext.get(el).parent('dd').dom.className='activ';
	if (classEl=='black') Ext.get(el).parent('dd').dom.className='black activ';
	if (classEl=='activ') Ext.get(el).parent('dd').dom.className='';
	if (classEl=='black activ') Ext.get(el).parent('dd').dom.className='black';
}

function showHideText(el,mode){
	//var parentEl = ;
	Ext.get(el).parent('p').dom.style.display='none';

	if (mode=='coll'){
		Ext.get(el).parent('p').prev().dom.style.display = 'block';
	}
	if (mode=='exp'){
		Ext.get(el).parent('p').next().dom.style.display = 'block';
	}
}

// end incorrect ad message

// userarea contact info
function sendUserareaContactInfoForm() {
	Ext.Ajax.request({
		form: 'userareaContactInfoForm',
		success: successContactInfoUpdate,
		failure: failureAlert,
		params: {action: 'contact_info'}
	});
	return false;
}

function sendUserareaUpdatePasswordForm() {
	hideAllErrorMessages();

	errors = false;

	old_password = document.getElementById('old_password');
	if(old_password.value.length < 6) {
		document.getElementById('wrong_old_password_error_message').style.display = 'block';
		errors = true;
	}

	password = document.getElementById('password');
	if(password.value.length == 0) {
		document.getElementById('empty_password_error_message').style.display = 'block';
		errors = true;
	}

	passwordConfirm = document.getElementById('passwordConfirm');
	if(passwordConfirm.value.length == 0) {
		document.getElementById('empty_confirm_password_error_message').style.display = 'block';
		errors = true;
	}

	if(passwordConfirm.value != password.value) {
		document.getElementById('wrong_confirm_password_error_message').style.display = 'block';
		errors = true;
	}

	if(errors) {
		document.getElementById('errors_panel').style.display = 'block';
		return false;
	}

	Ext.Ajax.request({
		form: 'userareaUpdatePasswordForm',
		success: successPasswordUpdate,
		failure: failureAlert,
		params: {action: 'password'}
	});
	return false;
}

function successPasswordUpdate(response, options) {
	hideAllErrorMessages();
	var res = Ext.decode(response.responseText);
	if(res.success==true){
		document.getElementById('update_password_success_message').style.display = 'block';
		document.getElementById('update_user_info_success_message').style.display = 'none';
		update_logo_message = document.getElementById('update_logo_success_message');
		if(update_logo_message) {
			update_logo_message.style.display = 'none';
		}

		document.getElementById('alerts').style.display = 'none';
		document.getElementById('errors_panel').style.display = 'none';
		document.getElementById('message_panel').style.display = 'block';

		document.getElementById('changePasswordBlock').style.display = 'none';
		document.getElementById('changePasswordLink').style.display = 'block';
	}else{
		document.getElementById('message_panel').style.display = 'none';
		showRegisterErrors(res.errors);
	}
	return false;
}

function hideAllSuccessMessages(){
	document.getElementById('message_panel').style.display = 'none';

	box = document.getElementById('message_panel');
	for(i=0; i<box.childNodes.length; i++) {
		if(box.childNodes[i].id) {
			box.childNodes[i].style.display = "none";
		}
	}
}

function successContactInfoUpdate(response, options) {
	hideAllErrorMessages();
	var res = Ext.decode(response.responseText);
	hideAllSuccessMessages();
	if(res.success==true){
		document.getElementById('update_user_info_success_message').style.display = 'block';

		document.getElementById('alerts').style.display = 'none';
		document.getElementById('errors_panel').style.display = 'none';
		document.getElementById('message_panel').style.display = 'block';

		document.getElementById('changePasswordBlock').style.display = 'none';
		document.getElementById('changePasswordLink').style.display = 'block';

	}else{
		showRegisterErrors(res.errors);
	}
	return false;
}

function successLogoUpdate(){
	hideAllSuccessMessages();
	document.getElementById('update_logo_success_message').style.display = 'block';

	document.getElementById('alerts').style.display = 'none';
	document.getElementById('errors_panel').style.display = 'none';
	document.getElementById('message_panel').style.display = 'block';

	document.getElementById('changeLogoBlock').style.display = 'none';
	document.getElementById('changeLogoLink').style.display = 'block';
}

function refreshLogo(url){
	img = $('img_logo');
	if(img == null) {
		elImg = document.createElement('IMG');
		elImg.id='img_logo';
		$('logo_block').appendChild(elImg);
	}
	$('img_logo').src = url;
}

function failureLogoUpdate(elem)
{
	$('message_panel').style.display = 'none';

	hideAllErrorMessages();
	$('errors_panel').style.display = 'block';
	$(elem).style.display = 'block';
}


function goToUserareaAds() {
	goTo('/myadverts/');
}

function curUrl() {
	var url = document.location.href;
	url = url.replace(/\?return=.*/,'');
	url = url.replace(/http:\/\/.*?\//,"");
	if(url.match(/logout=1/)) url = '';
	if(url.match(/login/)) url = '';
	if ($('site_cookie_path')) {
		pathCookie = $('site_cookie_path').value;
	} else {
		pathCookie = false;
	}
	setCookie2('returnPath', 'http://'+window.location.hostname+'/?return=/'+url, 0, '/', pathCookie);
	goTo('http://'+window.location.hostname+'/login/?return=/'+url);
}
function curUrlDomain(host_name) {
	var url = document.location.href;
	url = url.replace(/\?return=.*/,'');
	url = url.replace(/http:\/\/.*?\//,"");
	if(url.match(/logout=1/)) url = '';
	if(url.match(/login/)) url = '';
	if ($('site_cookie_path')) {
		pathCookie = $('site_cookie_path').value;
	} else {
		pathCookie = false;
	}
	if (host_name!=window.location.hostname){
		var temp = window.location.hostname.match(/([a-z]+[A-Z]+[0-9]*)/ig);
		url = url+'&domain='+temp[0];
		var replace = temp[0]+'.';
		setCookie2('returnPath', 'http://'+window.location.hostname.replace(replace,'')+'/?return=/'+url, 0, '/', pathCookie);
		goTo('http://'+window.location.hostname.replace(replace,'')+'/login/?return=/'+url);
	}
	else {
		setCookie2('returnPath', 'http://'+window.location.hostname+'/?return=/'+url, 0, '/', pathCookie);
		goTo('http://'+window.location.hostname+'/login/?return=/'+url);
	}
	//	console.log('http://'+window.location.hostname.replace(replace,'')+'/login/?return=/'+url);
}

function showPasswordFields() {
	document.getElementById('changePasswordBlock').style.display = 'block';
	document.getElementById('changePasswordLink').style.display = 'none';
}

function deletePsellerLogo()
{
	Ext.Ajax.request({
		url: '/ajax/userareaInfo.php',
		success: successDeleteLogo,
		failure: failureAlert,
		params: {action: 'delete_pseller_logo'}
	});
}

function successDeleteLogo()
{
	hideAllSuccessMessages();
	img = $('img_logo');
	if(img != null){
		img.src = '';
		document.getElementById('delete_logo_success_message').style.display = 'block';
		document.getElementById('message_panel').style.display = 'block';

		document.getElementById('changeLogoBlock').style.display = 'none';
		document.getElementById('changeLogoLink').style.display = 'block';
	}
}
// end userarea contact info

// link to friend
function sendLink2FriendForm(id, btn) {
	var oldValue = btn.value;
	btn.value = 'Ждите...';
	btn.disabled = true;
	Ext.get(btn).parent('div').replaceClass('btn-a', 'btn-b');

	Ext.Ajax.request({
		form: 'linktofriendForm',
		success: function(response,options){successLink2FriendForm(response,options, btn);},
		failure: function(response,options){failureLink2FriendForm(response,options, btn);},
		params: {action: 'l2f', 'ad_id': id}
	});
	return false;
}
function successLink2FriendForm(response, options, btn) {
	btn.value = 'Отправить';
	btn.disabled = false;
	Ext.get(btn).parent('div').replaceClass('btn-b', 'btn-a');

	var res = Ext.decode(response.responseText);
	if(res.success==true){
		alert('Сообщение отправлено');
		hideIconErrs('linktofriendForm');
		goTo('/advert/'+res.ad_id+'/');
	}else{
		showIconErrs(res.errors, 'l2f_');
		alert('Заполните обязательные поля');
	}
}
function failureLink2FriendForm(response, options, btn) {
	btn.value = 'Отправить';
	btn.disabled = false;
	Ext.get(btn).parent('div').replaceClass('btn-b', 'btn-a');

	alert('Ошибка связи. Попробуйте повторить действие через несколько минут.');
}
// end link to friend

function setCookie2 (name, value, expires, path, domain, secure) {
	if (!path && $('default_cookie_path')) {
		path=$('default_cookie_path').value;
	}
	if (!domain && $('site_cookie_path')) {
		domain=$('site_cookie_path').value;
	}
	document.cookie = name + "=" + escape(value) +
	((expires) ? "; expires=" + expires : "") +
	((path) ? "; path=" + path : "") +
	((domain) ? "; domain=" + domain : "") +
	((secure) ? "; secure" : "");
}

function getCookie2(name) {
	var cookie = " " + document.cookie;
	var search = " " + name + "=";
	var setStr = null;
	var offset = 0;
	var end = 0;
	if (cookie.length > 0) {
		offset = cookie.indexOf(search);
		if (offset != -1) {
			offset += search.length;
			end = cookie.indexOf(";", offset);
			if (end == -1) {
				end = cookie.length;
			}
			setStr = unescape(cookie.substring(offset, end));
		}
	}
	return(setStr);
}


function show_need_prices(my_curr){
	var coll = document.getElementsByTagName("span");
	for(var i=0; i<coll.length; i++){
		if (coll[i].className == "RUR" || coll[i].className == "USD" || coll[i].className == "EUR" || coll[i].className == "DEFAULT"){
			coll[i].style.display = "none";
		}
	}
	for(var i=0; i<coll.length; i++){
		if (coll[i].className == my_curr){
			coll[i].style.display = "inline";
		}
	}
}

function show_need_links(my_curr){
	var btn_rur = document.getElementById('RUR');
	var btn_usd = document.getElementById('USD');
	var btn_eur = document.getElementById('EUR');
	var btn_def = document.getElementById('DEFAULT');
	var btn_need = document.getElementById(my_curr);
	if (my_curr == "DEFAULT"){
		btn_rur.className = "";
		btn_rur.style.cursor = "pointer";
		btn_rur.style.display = "";

		btn_usd.className = "";
		btn_usd.style.cursor = "pointer";
		btn_usd.style.display = "";

		btn_eur.className = "";
		btn_eur.style.cursor = "pointer";
		btn_eur.style.display = "";

		btn_def.className = "";
		btn_def.style.display = "none";
	}
	else {
		btn_rur.className = "";
		btn_rur.style.cursor = "pointer";
		btn_rur.style.display = "none";

		btn_usd.className = "";
		btn_usd.style.cursor = "pointer";
		btn_usd.style.display = "none";

		btn_eur.className = "";
		btn_eur.style.cursor = "pointer";
		btn_eur.style.display = "none";

		btn_def.className = "";
		btn_def.style.cursor = "pointer";
		btn_def.style.display = "none";

		btn_need.className = "selected";
		btn_need.style.cursor = "default";
		btn_need.style.display = "";
		btn_def.style.display = "";
	}
}

function ch_m(my_curr){
	if (my_curr != "") {
		setCookie2("curr_currency", my_curr);
	}
	else {
		my_curr = getCookie2("curr_currency");
	}
	if (my_curr != null) {
		show_need_prices (my_curr);
		show_need_links (my_curr);
	}
}

function goToMyHighlight(id) {
	Ext.Ajax.request({
	url: '/ajax/check_payment.php',
	success: function(response) {
		var res = Ext.decode(response.responseText);
		if(res.success > 0){
	goTo('/myadverts/highlight/'+id+'/');
		}else{
			alert(res.message || 'Ошибка. Свяжитесь с администратором');
		}
	},
	failure: function(response) { },
	headers: {},
	params: {
		op:'has_pay',
		id:id
	}
	});

	return false;
}

function goToMyPushUp(id) {
	goTo('/myadverts/pushup/'+id+'/');
	return false;
}

function goToMyPremium(id) {
	goTo('/myadverts/premium/'+id+'/');
	return false;
}

function goToMyProlong(id,ispay) {
	//if(ispay) goTo('/myadverts/prolong/'+id+'/');
	//else {
	Ext.Ajax.request({
		url: '/ajax/payment.php',
		success: function(response) {
			var res = Ext.decode(response.responseText);
			if(res.success > 0){
				updFinDate(res);
				showMsgBox('ad_prolong');
			}else if(res.success == -3){
				showMsgBox('ad_err_activatelimit');
			}else if(res.success == -5){
				goTo(res["goto"]);
			}else{
				alert(res.message || 'Ошибка. Свяжитесь с администратором');
			}
		},
		failure: function(response) { },
		headers: {},
		params: {
			op:'prolong',
			js:1,
			id:id
		}
	});
	//}
	return false;
}

function updFinDate(res) { Ext.get('fin'+res.id).update(res.to); }
function setHPP(tr, id, ispay, btns) {
	var li = tr.child('li.lft');
	li.insertHtml('beforeBegin', btns);
	//li.insertHtml('beforeBegin', '<li class="lft"><div class="button-style btn-c" style="width:67px"><i></i><span><input type="button" value="ВЫДЕЛИТЬ" onclick="return goToMyHighlight('+id+');" /></span></div></li><li class="lft"><div class="button-style btn-c" style="width:64px"><i></i><span><input type="button" value="ПОДНЯТЬ" onclick="return goToMyPushUp('+id+');" /></span></div></li><li class="lft"><div class="button-style btn-c" style="width:69px"><i></i><span><input type="button" value="ПРОДЛИТЬ" onclick="return goToMyProlong('+id+','+ispay+');" /></span></div></li>');
	li.remove();
}

function goToMyActivate(inp,id,ispay) {
	//if(ispay) goTo('/myadverts/activate/'+id+'/');
	//else {
	Ext.Ajax.request({
		url: '/ajax/payment.php',
		success: function(response) {
			var res = Ext.decode(response.responseText);
			if(!res.success) {
				showMsgBox('ad_err_activate');
			}else if(res.success > 0){
				var tr = Ext.get('tit'+id).parent('tr');
				var tmp = tr.child('div.no-active');
				//if(tmp) tmp.parent().update('<div class="yes-active"><span class="ico-set"></span>активно</div>'+res.status);
				if(tmp) tmp.parent().update(res.status);
				var del = tr.next().child('div[align=right]');
				if(del) del.remove();
				setHPP(tr.next('tr'), res.id, res.ispay, res.btns);
				updFinDate(res);
			}else if(res.success == -5){
				goTo(res["goto"]);
			}else if(res.success == -3){
				showMsgBox('ad_err_activatelimit');
			}else if(res.success == -1){
				var tit = Ext.get('tit'+id);
				var tmp = tit.first('.warn');
				if(tmp) tmp.remove();
				tit.insertHtml('beforeEnd','<div class="warn">Ваше объявление отклонено модератором. Если вы хотите сделать объявление активным, пожалуйста, отредактируйте его.</div>');
			}
		},
		failure: function(response) {},
		headers: {},
		params: {
			op:'activate',
			js:1,
			id:id
		}
	});
	//}
	return false;
}

function showMsgBox(id) {
	alert(Ext.get(id).dom.innerHTML);
}

function $(id){
	return (typeof(id)=="object" ? id : document.getElementById(id));
}

function elHide(id){
	if ($(id)) {
		$(id).style.display="none";
	}
}

function elShow(id,inline){
	if ($(id)) {
		if (inline) {
			$(id).style.display="inline";
		} else {
			$(id).style.display="block";
		}
	}
}

function sh(id, cls) {
	var el = $(id), cl = 'none';
	var p = Ext.get(el).parent();
	if(el.style.display == 'none') {
		cl = 'block';
		p.addClass(cls);
	} else {
		p.removeClass(cls);
	}
	el.style.display = cl;
}

function hideMainFilters(){
	elHide('more-filters');
	elHide('extend-search');
	elHide('hideButton');
	elHide('hideButton1');
	elHide('close_bf');
	elShow('simple-search');
	if ($('site_cookie_path')) {
		$pathCookie=$('site_cookie_path').value;
	} else {
		$pathCookie=false;
	}
	setCookie2('filterFormStyle',0,false,'/',$pathCookie);

}

function showMainFilters(){
	elHide('simple-search');
	elShow('extend-search');
	elShow('hideButton');
	elShow('hideButton1');
	elShow('close_bf');
	elShow('mainFiltersButtonBlock');
	elHide('mainFiltersButtonBlock2');
	if ($('site_cookie_path')) {
		$pathCookie=$('site_cookie_path').value;
	} else {
		$pathCookie=false;
	}

	setCookie2('filterFormStyle',1,false,'/',$pathCookie);
}

function showMoreFilters(){
	elShow('more-filters');
	elHide('mainFiltersButtonBlock');
	elShow('mainFiltersButtonBlock2');
	if ($('site_cookie_path')) {
		$pathCookie=$('site_cookie_path').value;
	} else {
		$pathCookie=false;
	}
	setCookie2('filterFormStyle',2,false,'/',$pathCookie);
}

function hideMoreFilters(){
	elHide('more-filters');
	elHide('mainFiltersButtonBlock2');
	elShow('mainFiltersButtonBlock');
	if ($('site_cookie_path')) {
		$pathCookie=$('site_cookie_path').value;
	} else {
		$pathCookie=false;
	}
	setCookie2('filterFormStyle',1,false,'/',$pathCookie);
}



function showSecretFilter(){
	elShow('more-filters');
	elHide('mainFiltersButtonBlock');
	elShow('mainFiltersButtonBlock2');
	if ($('site_cookie_path')) {
		$pathCookie=$('site_cookie_path').value;
	} else {
		$pathCookie=false;
	}
	setCookie2('filterFormStyle',2,false,'/',$pathCookie);
}

function hideSecretFilter(){
	elHide('more-filters');
	elHide('mainFiltersButtonBlock2');
	elShow('mainFiltersButtonBlock');
	if ($('site_cookie_path')) {
		$pathCookie=$('site_cookie_path').value;
	} else {
		$pathCookie=false;
	}
	setCookie2('filterFormStyle',1,false,'/',$pathCookie);
}




function resetFilters(formName){
	var elements=$(formName).elements;
	for (el in elements) {
		if (!elements[el]) continue;
		elName=elements[el].name;
		elTagName = elements[el].tagName;
		if ($(elName+"_value_1")) {
			//			setFilterValue(elName,elements[el].value,$(elName+"_value_1").firstChild, formName);
			clearFilterValue(elName,formName);
		}
		if ('INPUT' == elTagName) {
			switch(elements[el].type) {
				case 'text':
				elements[el].value = ''; break;
				case 'checkbox':elements[el].checked = false; break;
				case 'radio':
				elements[el].checked = false; break;
				case 'hidden':
				if(elements[el].getAttribute('reseter')) { callbackCleaner(elements[el]); continue; }
				break;
			}
		}
		if (elements[el].id =='filter_psellers'){
			elements[el].selectedIndex = -1;
			elements[el].style.display = 'none';
		}else if ('SELECT' == elTagName) {
			elements[el].selectedIndex = 0;
		}
	}
	var mass_cust = new Array(
		new Array ("bodytype", "любой"),
		new Array ("transmittion", "любой"),
		new Array ("gear", "любой"),
		new Array ("fuel", "любой"),
		new Array ("bustype", "любой"),
		new Array ("cabtype", "любой"),
		new Array ("special-type", "любой")	,
		new Array ("trailertype", "любой"),
		new Array ("recordplayer_type", "любой"),
		new Array ("ram_size", "любой"),
		new Array ("type", "любой"),
		new Array ("application", "любое"),
		new Array ("covering", "любое"),
		new Array ("material", "любое"),
		new Array ("wireless_interfaces", "любое"),
		new Array ("mv_wireless_interfaces", "любое"),		
		new Array ("mv_type", "любой"),
		new Array ("mv_multitype", "любой"),
		new Array ("condition", "любое")
	);
	for (x = 0; x < mass_cust.length; x++){
	 var el=document.getElementById(mass_cust[x][0]);
     if(el) {
    	el.innerHTML=mass_cust[x][1];
     }
	}
/*    var bodytype=document.getElementById("bodytype");
    if(bodytype) {
    	bodytype.textContent='любой';
    }*/
	Ext.each(Ext.query( "span/i/a" ), function(a){a.onclick();});
	Ext.each(Ext.query('span[@id^=region_]/span[class=selected]/a', $(formName)), function(o){o.onclick();});
}

function resetMetro(el) {
	var id = el.name.split('_')[2];
	el.value='';
	last_region_id = id;
	var p = el.getAttribute('resetparams');
	if(p != '' && p !== null) {
		p = p.split(',');
		var li;
		for (var j = p.length; --j >= 0;) { li=$('place_value_'+p[j]); if(li) li.className=''; }
	}
	setFilterRegionTxt(getRegionType(id), [el, id]);
}

function resetZones(el) {
	Ext.each(Ext.query("li[id^=place_value_][class=selected]/a"), function(o) {
		o.onclick();
	});
}

function callbackCleaner(el) {
	var fnk = el.getAttribute('reseter');
	eval(fnk+'(el)');
}

function clearFilterValue(name,formName){
	i=1;
	$(formName)[name].value='';
	Ext.each(Ext.query("*[id^="+name+"_value_]",$(formName)), function(el) { el.className = ''; });
}

function setFilterValue(name,value,el,formName){
	if(!el) return false;

	if($(formName)[name].value==value && el.parentNode.className=='selected') {
		clearFilterValue(name,formName);
		return;
	}

	clearFilterValue(name,formName);
	$(formName)[name].value=value;
	el.parentNode.className='selected';
}

function restoreMultiFilterValue(name,arr,formName){
	if(Ext.query("form[id="+formName+"]")=='') formName = 'subscriptionForm';
	var v = $(formName)[name].value;
	if(v!='') {
		v = v.split(',');
		var pos;
		for(var i=0; i<v.length; i++) {
			if((pos = arr.indexOf(v[i])) > -1) mysetFilterValue(name, v[i], $(name+'_value_'+pos).firstChild, formName);
		}
	}
}

function deleteValFromField(formName, name, value) {
	var elval = $(formName)[name].value;
	if(elval == '') return;
	elval = elval.split(',');
	if(typeof(value)=='object') {
		for (var j = value.length; --j >= 0;) elval.remove(''+value[j]);
	} else {
		elval.remove(''+value);
	}
	$(formName)[name].value = elval.join(',');
}

function mysetFilterValue(name,value,el,formName){
	if(!el) return false;
	if (el == "restore" || el == "setonly"){
		if(el == "restore") $(formName)[name].value = "";
		var rooms = value.split(",");
		for (x = 0; x < rooms.length; x++){
			var tmp;
			if(tmp = $(name+'_value_'+rooms[x])) {
				mysetFilterValue (name, rooms[x], tmp.firstChild, formName);
			}
		}
		return 1;
	}
	if($(formName)[name].value.indexOf(value) > -1 && el.parentNode.className=='selected') {
		el.parentNode.className = '';

		deleteValFromField(formName, name, value);
		return 2;
	}
	if($(formName)[name].value == ""){$(formName)[name].value=value;}
	//else if($(formName)[name].value.indexOf(value) == -1) {$(formName)[name].value += ','+value;}
	else if(!(new RegExp("(^|,)"+value+"(,|$)")).test($(formName)[name].value)) {$(formName)[name].value += ','+value;}
	$(formName)[name].value = $(formName)[name].value.replace (/\,,/, ",");
	el.parentNode.className='selected';
}

var my_timer, my_timer1, timer, prev_id;

function showFiltersPriceSelect(){
	if (my_timer){clearTimeout(my_timer);}
	elShow('select_price');
}
function hideFiltersPriceSelect(){
	my_timer = setTimeout ("elHide('select_price');", 500);
}

function setFiltersPrice(value, el){
	el.value=value;
	elHide('select_price');
}

function setFiltersCustomPrice(el){
	from=$('custom_price_from').value;
	fromN=Number(from);
	to=$('custom_price_to').value;
	toN=Number(to);
	value='';
	if (from!='') {
		if ((to=='' || toN<fromN)) {
			value = 'больше ' + fromN;
		} else {
			value += 'от '+ from;
		}
	}
	if (to!=''){
		if (toN>fromN) {
			if (fromN==0) {
				value = 'меньше ' + toN;
			} else {
				value += ' до '+ to;
			}
		}
	}
	if (from == to) {
		value = from;
	}
	if (value==''){
		value="любая";
	}
	el.value=value;
	elHide('select_price');
}





function showFiltersRangeSelect(id){
	if (timer && prev_id == id){clearTimeout(timer);}
	elShow(id);
}
function hideFiltersRangeSelect(id){
	timer = setTimeout("elHide('"+id+"');", 500);
	prev_id = id;
}
function showFiltersRangeSel(id){
	if (my_timer1){clearTimeout(my_timer1);}
	elShow(id);
}

function hideFiltersRangeSel(id){
	my_timer1 = setTimeout ("elHide('"+id+"');", 500);
}

function setFiltersRange(id, value, el){
	el.value=value;
	elHide(id);
}

function setFiltersCustomRange(el,isfloat){
	from=($('custom_' + el.id +'_from').value).replace(',','.');
	fromN=(isfloat ? from.filterFloat() : Number(from));
	fromNN=(isfloat ? parseFloat(from) : Number(from));

	to=($('custom_' + el.id +'_to').value).replace(',','.');
	toN=(isfloat ? to.filterFloat() : Number(to));
	toNN=(isfloat ? parseFloat(to) : Number(to));
	value='';
	if (from!='') {
		if ((to=='' || toNN<fromNN)) {
			value = 'больше ' + fromN;
		} else {
			value += 'от '+ fromN;
		}
	}
	if (to!=''){
		if (toNN>fromN) {
			if (fromNN==0) {
				value = 'меньше ' + toN;
			} else {
				value += ' до '+ toN;
			}
		}
	}
	if (from == to) {
		value = fromN;
	}
	if (value==''){
		value="любая";
	}
	el.value=value;
	elHide('select_' + el.id +'');
}

function setFiltersDeadlineRange(name){
	//deadline_quarter_from
	from = ($(name +'_year_from').value);
	if (from){
		from += '.' + ($(name +'_quarter_from').value || 0);
	}

	to = ($(name +'_year_to').value);
	if (to){
		to += '.' + ($(name +'_quarter_to').value || 0);
	}

	value='';
	if (from!='') {
		if ((to=='' || to<from)) {
			value = 'больше ' + from;
		} else {
			value += 'от '+ from;
		}
	}
	if (to!=''){
		if (to>from) {
			if (from==0) {
				value = 'меньше ' + to;
			} else {
				value += ' до '+ to;
			}
		}
	}
	if (from == to) {
		value = from;
	}

	return value;
}

function goTo(url) {
	window.location.href = url;
}

function getCategories(el) {
	$('waitMessage').style.display = '';
	Ext.Ajax.request({
		url: '/ajax/categories.php',
		success: successToGetCategories,
		failure: failureToGetCategories,
		params: {category: el.value}
	});
}

function updateCategories(aCategories) {
	var oCategories = $('oCategories');
	var el = document.createElement('OPTION');
	oCategories.innerHTML = '';
	el.value = '0';
	el.selected = true;
	el.appendChild(document.createTextNode('Выберите раздел'));
	oCategories.appendChild(el);
	for (var i = 0, n = aCategories.length; i < n; i ++) {
		el = document.createElement('OPTION');
		el.value = aCategories[i].uri;
		el.appendChild(document.createTextNode(aCategories[i].title));
		oCategories.appendChild(el);
	}
}

function successToGetCategories(response, options) {
	var res = Ext.decode(response.responseText);
	$('waitMessage').style.display = 'none';
	if (res && res.item && res.item.title) {
		var oCategoriesNavigation = $('categoriesNavigation');
		var oCategories = $('oCategories');
		var linkEl = document.createElement('A');
		linkEl.href = '/addAdvert/step1/?category=' + res.item.prev_uri;
		linkEl.onclick = function() { replaceAnchorBySelect(this); return false; };
		linkEl.appendChild(document.createTextNode(res.item.title));
		oCategoriesNavigation.appendChild(linkEl);
		linkEl = document.createTextNode(' ');
		oCategoriesNavigation.appendChild(linkEl);
		if (res.categories.length>0){
			var linkEl = document.createElement('SPAN');
			linkEl.className="blue";
			linkEl.appendChild(document.createTextNode('»'));
			oCategoriesNavigation.appendChild(linkEl);
			linkEl = document.createTextNode(' ');
			oCategoriesNavigation.appendChild(linkEl);

			updateCategories(res.categories);
		} else {
			oCategories.style.display = 'none';
			document.location = '/addAdvert/step2/?category=' + res.item.uri;
			$('waitMessage').style.display = '';
			return true;
		}
	} else {
		alert('Ошибка связи. Попробуйте повторить позже.');
	}
}

function getValueFromURL(name,str){
	urlChunk = str.split('?');
	if(!urlChunk[1]) return false;
	gets=urlChunk[1].split('&');
	for (i=0; i<gets.length; i++){
		getEl=gets[i].split('=');
		if (getEl[0]==name) {
			return getEl[1];
		}
	}
	return false;
}

/*********************/
function replaceAnchorBySelect(_this) {
	//wizardSelectCategory();

	var message = $('waitMessage');
	var oCategories = $('oCategories');
	var parentNode = _this.parentNode;
	var el = {};
	while (el = _this.nextSibling) {
		parentNode.removeChild(el);
	}

	if (arguments.length == 2) {
		var temp = arguments[1]; //for search alert editing
	}else{
		var temp = getValueFromURL('category', _this.href);
	}

	Ext.Ajax.request({
		url: '/ajax/categories.php',
		success: function(response, options) {
			var res = Ext.decode(response.responseText);
			if (res && res.categories && res.categories.length>0) {
				updateCategories(res.categories);
			} else {
				alert('Ошибка связи. Попробуйте повторить позже.');
			}
		},
		failure: failureToGetCategories,
		params: {category: temp}
	});

	parentNode.removeChild(_this);
	oCategories.style.display = '';

	return false;
}
/*********************/

function failureToGetCategories() {
	$('waitMessage').style.display = 'none';
	alert('Ошибка связи. Попробуйте повторить позже.');
}

function viewObject(name){
	var obj = eval(name), i;
	if(!obj) {
		alert("\""+name+"\" ia not an object");
		return;
	}
	var w_Test = open("","Test","width=600,height=500,scrollbars=1");
	if(!w_Test)	{
		alert("Cannot open window for "+name);
		return;
	}

	w_Test.document.open();

	for(i in obj) w_Test.document.write(name+"."+i+"="+obj[i]+"<br>");

	w_Test.document.close();
}


function closeSelectCols(){
	elHide('select_cols');
	elHide('select_cols_close');
}

function getMultiselected(opt){
	var selected = '';
	for (var intLoop=0; intLoop<opt.length; intLoop++) {
		if (opt[intLoop].selected || opt[intLoop].checked) {
			selected += opt[intLoop].value + ',';
		}
	}
	return selected.substring(0,selected.length-1);
}

function createFilter(el){
	//var preURL = el.action;
	var eqSymbol = '=';
	var url = '';
	var chSymbol = ',';
	var savedValues = new Object();
	var tmp;

	if (el.elements){
		//url = preURL;
		for (i=0; i<el.elements.length; i++){
			elName=el.elements[i].name;

			if (el.elements[i].getAttribute('skip')) continue;

			if(elName=='') {
				if(tmp = el.elements[i].getAttribute('fromto'))	{
					var res = {id: tmp, value: ''};
					setFiltersCustomRange(res, (el.elements[i].getAttribute('valtype')=='float'));
					if(res.value!='любая') {
						savedValues[tmp]=res.value;
					}
				}else if (t = el.elements[i].getAttribute('deadline')){
					var res = setFiltersDeadlineRange(t);
					if (res) savedValues[t]=res;
				}
			} else if (elName!='test' && elName!='test1' && elName.indexOf('sp_')!=0) {
				//alert(el.elements[i].name + ':' + Ext.get(el.elements[i]).isVisible());
				elValue=el.elements[i].value;

				if (el.elements[i].getAttribute('multiple')){
					elValue = getMultiselected(el.elements[i].options);
				}
				if (el.elements[i].type=='radio') {
					elValue=(el.elements[i].checked ? el.elements[i].value : '');
				}
				if (el.elements[i].type=='checkbox') {
					elValue=(el.elements[i].checked ? 1 : 0);
				}
				if ((el.elements[i].type=='checkbox'||el.elements[i].type=='hidden') && elName.indexOf('ch_')==0 && elValue!=0) {
					//tmp = elName.split('_');
					elChName = elName.match(/_(.*)_[^_]/)[1];

					if (savedValues[elChName]){
						savedValues[elChName]+=chSymbol+el.elements[i].value;
					} else {
						savedValues[elChName]=el.elements[i].value;
					}

					elValue='';
				}

				tmp = el.elements[i].getAttribute('valtype');
				if(tmp && tmp=='float') {
					elValue = tmp = el.elements[i].value;
					if(tmp = tmp.match(/([0-9]+(?:\.[0-9]+)?)/g)) {
						//for(var j=0;j<tmp.length;j++) {
						for (var j = tmp.length; --j >= 0;) {
							elValue=elValue.replace(String(tmp[j]), String(Math.abs(parseFloat(tmp[j])).toFixed(1)));
						}
					}
				}

				if (elValue!=''){
					if(el.elements[i].getAttribute('crc')) elValue = crc32(elValue);
					url+=elName+eqSymbol+encodeURIComponent(elValue)+"/";
				}
			}
		}

		for (elName in savedValues) {
			url+=elName+eqSymbol+encodeURIComponent(savedValues[elName])+"/";
		}
	}
	return url;
	//return false;
}

function submitFilters(form, form2){

	var form = form || $('filters');
	var basehref = '';
	basehref=form.action.replace('http://' + document.domain, '');

	var searchstring = createFilter(form);
	if(form2) {
		if(form2.id) {
			searchstring+= createFilter(form2);
		} else {
			for(var i=0;i<form2.length;i++)	searchstring+= createFilter(form2[i]);
		}
	}
	/*
	for(i=0; i<=5; i++){
		if($('sbutton'+i)){
			$('sbutton'+i).disabled='disabled';
		}
	}
	*/
	if(searchstring!=''){
		document.location = basehref + '/search/' + searchstring;
	}else{
		document.location = basehref + '/';
	}


	return false;
}


function submitPsellersSearch(){
	query_str = document.getElementById('query_string').value;
	if(query_str.length == 0) {
		return false;
	}

	if($('search_pselelrs').checked) {
		searchstring = '/powerSellers/list/search/keywords=' + encodeURIComponent(query_str) + '/';
		window.location = searchstring;
	} else if($('search_adverts').checked) {
		searchstring = '/powerSellers/ads_list/search/keywords=' + encodeURIComponent(query_str) + '/';
		window.location = searchstring;
	}
	return false;
}

function submitPowerAreaSearchForm()
{
	submitFilters($('psfilter'), $('filters'));

	//	query_str = document.getElementById('query_string').value;
	//	if(query_str.length == 0) {
	//		return false;
	//	}
	//
	//	searchstring = '/psellerAdverts/search/keywords=' + encodeURIComponent(query_str) + '/';
	//	window.location = searchstring;
}

function saveCustomColumns(){

	var form = $('customcolumns');
	var customColumns = new Array();
	for(i=0; i<form.elements.length; i++){
		//alert(form.elements[i].name);
		if(form.elements[i].checked){
			customColumns.push(form.elements[i].name);
		}
	}

	setCookie2('customcolumns', customColumns.toString());
	var currentLocation = location.href; 
	if(currentLocation.indexOf('/search/') != -1){
		document.location.reload();
	}else{
		if(currentLocation.substr(currentLocation.length - 1, 1) == '/'){
			document.location.replace(currentLocation + 'search/')
		}else{
			document.location.replace(currentLocation + '/search/')
		}
	}

	return false;
}

function openSelectCols(){
	if ($('select_cols').style.display!='block') {
		elShow('select_cols');
		elShow('select_cols_close');
	} else {
		closeSelectCols();
	}
}



function getRegions(el, uniid) {
	if(!uniid) uniid = '';

	$('waitMessageRegions'+uniid).style.display = '';
	Ext.Ajax.request({
		url: '/ajax/regions.php',
		success: function(uniid) { return function(response, options) { successToGetRegions(response, options, uniid); } }(uniid),
		failure: failureToGetRegions,
		params: {region: el.value}
	});
}

function updateRegions(aRegions, uniid) {
	if(!uniid) uniid = '';

	var oRegions = $('oRegions'+uniid);
	var el = document.createElement('OPTION');

	oRegions.innerHTML = '';
	el.value = '0';
	el.selected = true;

	if('Авиамоторная м.' == aRegions[0].title || 'Автово м.' == aRegions[0].title)
	el.appendChild(document.createTextNode('Выберите район'));
	else
	el.appendChild(document.createTextNode('Выберите регион'));

	oRegions.appendChild(el);

	for (var i = 0, n = aRegions.length; i < n; i ++) {
		el = document.createElement('OPTION');
		el.value = aRegions[i].uri;
		el.appendChild(document.createTextNode(aRegions[i].title));
		oRegions.appendChild(el);
	}
}

function successToGetRegions (response, options, uniid) {
	if(!uniid) uniid = '';

	var res = Ext.decode(response.responseText);

	if(res.item.uri.split('/').length <= 3) getAdAddStatus(res.item.uri);

	$('waitMessageRegions'+uniid).style.display = 'none';
	if (res && res.item && res.item.title) {
		$('id_region'+uniid).value=res.item.uri;
		if($('addr_string'+uniid)) $('addr_string'+uniid).value=res.item.addr_string;
		var oRegionsNavigation = $('regionsNavigation'+uniid);
		var oRegions = $('oRegions'+uniid);
		var linkEl = document.createElement('A');
		linkEl.href = '?region=' + res.item.prev_uri;
		linkEl.onclick = function() { replaceAnchorBySelectRegions(this, uniid); return false; };
		linkEl.appendChild(document.createTextNode(res.item.title));
		oRegionsNavigation.appendChild(linkEl);
		linkEl = document.createTextNode(' ');
		oRegionsNavigation.appendChild(linkEl);
		if (res.regions.length>0){
			var linkEl = document.createElement('SPAN');
			linkEl.className="blue";
			linkEl.appendChild(document.createTextNode('»'));
			oRegionsNavigation.appendChild(linkEl);
			linkEl = document.createTextNode(' ');
			oRegionsNavigation.appendChild(linkEl);

			updateRegions(res.regions, uniid);
		} else {
			oRegions.style.display = 'none';
			return true;
		}
	} else {
		alert('Ошибка связи. Попробуйте повторить позже.');
	}
}


function replaceAnchorBySelectRegions(_this, uniid) {
	//wizardSelectCategory();
	if(!uniid) uniid = '';
	var message = $('waitMessageRegions'+uniid);
	var oRegions = $('oRegions'+uniid);
	var parentNode = _this.parentNode;
	var el = {};
	while (el = _this.nextSibling) {
		parentNode.removeChild(el);
	}
	var new_uri = getValueFromURL('region',_this.href);
	Ext.Ajax.request({
		url: '/ajax/regions.php',
		success: function(response, options) {
			var res = Ext.decode(response.responseText);
			if (res && res.regions && res.regions.length>0) {
				$('id_region'+uniid).value=res.item.uri;
				updateRegions(res.regions, uniid);
			} else {
				alert('Ошибка связи. Попробуйте повторить позже.');
			}
		},
		failure: failureToGetRegions,
		params: {region: new_uri}
	});

	if(new_uri.split('/').length <= 3) getAdAddStatus(new_uri);

	parentNode.removeChild(_this);
	oRegions.style.display = '';

	if(typeof(replaceAnchorBySelectRegions_hook) == 'function') replaceAnchorBySelectRegions_hook();

	return false;
}

function failureToGetRegions() {
	$('waitMessageRegions').style.display = 'none';
	alert('Ошибка связи. Попробуйте повторить позже.');
}

function filterInteger(event) {
	var keyCode = (event.charCode) ? event.charCode : event.keyCode;
	return (((event.keyCode == 46) && !Ext.isIE) || (keyCode == 63275) || (keyCode == 0) || (keyCode == 8) || (keyCode == 9) || (keyCode == 37) || (keyCode == 39) || (keyCode > 47 && keyCode < 58));
}

function filterFloat(event) {
	var keyCode = (event.charCode) ? event.charCode : event.keyCode;
	return ((keyCode == 44) || (keyCode == 46) || (keyCode == 63275) || (keyCode == 0) || (keyCode == 8) || (keyCode == 9) || (keyCode == 37) || (keyCode == 39) || (keyCode > 47 && keyCode < 58));
}

function filterPhone(event) {
	var keyCode = (event.charCode) ? event.charCode : event.keyCode;
	return ((keyCode == 40) || (keyCode == 63275) || (keyCode == 41) || (keyCode == 43) || (keyCode == 45) || (keyCode == 46) || (keyCode == 0) || (keyCode == 8) || (keyCode == 9) || (keyCode == 37) || (keyCode == 39) || (keyCode > 47 && keyCode < 58));
}

function filterIcq(event) {
	var keyCode = (event.charCode) ? event.charCode : event.keyCode;
	return ((keyCode == 45) || (keyCode == 63275) || (keyCode == 46) || (keyCode == 0) || (keyCode == 8) || (keyCode == 9) || (keyCode == 37) || (keyCode == 39) || (keyCode > 47 && keyCode < 58));
}

function formAddSubmit(objForm, dontSkipEmpty, btn){
	elForm = objForm.getForm();
	flagSend=true;
	if (necessaryFields && necessaryFields.length>0){
		for (i=0; i<necessaryFields.length; i++) {
			if ($('id_'+necessaryFields[i])) {
				el=$('id_'+necessaryFields[i]);
				if (el.value=='') {
					markFieldInvalid(el.parentNode);
					if (flagSend) objForm.showError('Заполните обязательные поля');
					flagSend=false;
				}
			}
		}
	}

	if (flagSend) objForm.hideError();
	flagSend &= objForm.fireEvent('fields_checked');

	if (flagSend){
		var eqSymbol = '=';
		var params = new Array();
		if (elForm.elements){
                        //подсчет количества элементов вручную (ie bug). Проблема возникает при наличии поля с названием "length"
                        var cnt = 0;
                        while(elForm.elements[cnt] != undefined) {
                            cnt++;
                        }
			//for (i=0; i<elForm.elements.length; i++){
                        for (i=0; i<cnt; i++){
				elName=elForm.elements[i].name;
				if (elName && elName!='') {
					elValue=elForm.elements[i].value;
					if (elForm.elements[i].type=='checkbox') {
						elValue=(elForm.elements[i].checked ? 1 : 0);
					}
					if (elValue!='' || dontSkipEmpty){
						params[elName]=encodeURIComponent(elValue);
					}
				}
			}
		}

		//params = formAddOther(params);

		var oldValue = btn.value;
		btn.value = 'Ждите...';
		btn.disabled = true;
		Ext.get(btn).parent('div').replaceClass('btn-a', 'btn-b');

		Ext.Ajax.request({
			url: elForm.action,
			success: function(response, options) {

				var res = Ext.decode(response.responseText);

				if (res.isedit && res.success) { goTo(res.url); }
				else if (!res.isedit && res.success && res.ad_id) {
					if(res.message) alert(res.message);
					goTo('/addAdvert/step3/?id=' + res.ad_id);
				}else if(res.inerror) {
					if(res.inerror==1) {
						var p = Ext.get('categoriesNavigation').parent();
					} else {
						var p = Ext.get(elForm);
					}
					var ul = p.prev('ul'); if(ul) ul.remove();
					p.insertHtml('beforeBegin',res.message);
					window.scrollTo(0, p.parent().getY());

				}else{
					alert('Ошибка. ' + res.message);
				}
				btn.value = oldValue;
				btn.disabled = false;
				Ext.get(btn).parent('div').replaceClass('btn-b', 'btn-a');
			},
			failure:  function(response, options) {
				btn.value = oldValue;
				btn.disabled = false;
				Ext.get(btn).parent('div').replaceClass('btn-b', 'btn-a');
				alert('Ошибка связи. Попробуйте повторить позже.');
			},
			params: params
		});
	}

	return false;
}

function formAddCommentSubmit(elForm,id){
	if($('comment_'+id).value=='')
	{alert('Заполните поле ответа!'); return;}

	var params = new Array();
	params['comment']=$('comment_'+id).value;
	params['ref_id']=$('ref_id_'+id).value;

	Ext.Ajax.request({
		url: elForm.action,
		success: function(response, options) {
			var res = Ext.decode(response.responseText);
			if (res.success) {
				alert("Ваш ответ добавлен.");
				document.location.reload();
			}
			else alert('Ошибка. ' + res.message);
		},
		failure:  function(response, options) {
			alert('Ошибка связи. Попробуйте повторить позже.');
		},
		params: params
	});

	return false;
}
function formAddComment(elForm){
	if($('author_id') && $('author_id').value.trim()=='')
		{alert('Заполните поле "Представьтесь, пожалуйста"!'); return;}
	if($('comment_text_id') && $('comment_text_id').value.trim()=='')
		{alert('Заполните поле комментария!'); return;}

	var params = new Array();
	if (elForm.elements){
		for (i=0; i<elForm.elements.length; i++){
			elName=elForm.elements[i].name;
			if (elName && elName!='') {
				elValue=elForm.elements[i].value;
				 if (elValue!=''){
					params[elName]=elValue;
				}
			}
		}
	}
	if($('add_butt_comment')){
		$('add_butt_comment').value="Ждите...";
		$('add_butt_comment').disabled=true;
	}
	Ext.Ajax.request({
		url: elForm.action,
		success: function(response, options) {
			var res = Ext.decode(response.responseText);
			if (res.success) {
				displayCommentAdd(elForm.id);
				elForm.reset();
				alert("Комментарий был добавлен");
				location.reload();
			}
			else alert('Ошибка. ' + res.message);
			if($('add_butt_comment')){
				$('add_butt_comment').value="Добавить";
				$('add_butt_comment').disabled=false;
			}
		},
		failure:  function(response, options) {
			alert('Ошибка связи. Попробуйте повторить позже.');
			if($('add_butt_comment')){
				$('add_butt_comment').value="Добавить";
				$('add_butt_comment').disabled=false;
			}
		},
		params: params
	});

	return false;
}
function displayCommentAdd(form){
	var divCommentAdd = Ext.get(form+'_div').dom;
	var no = (divCommentAdd.style.display == 'none');
	divCommentAdd.style.display = (no ? 'block' : 'none');
}

function formAddRefSubmit(elForm){
	if((elForm.id=='form_add_ref' && $('ref_name').value.trim()=='') || (elForm.id=='form_add_ref_down' && $('ref_name_down').value.trim()==''))
	{alert('Заполните поле "Ваше имя"!'); return;}
	if((elForm.id=='form_add_ref' && $('ref_text').value.trim()=='') || (elForm.id=='form_add_ref_down' && $('ref_text_down').value.trim()==''))
	{alert('Заполните поле "Отзыв"!'); return;}
	var params = new Array();
	if (elForm.elements){
		for (i=0; i<elForm.elements.length; i++){
			elName=elForm.elements[i].name;
			if (elName && elName!='') {
				elValue=elForm.elements[i].value;
				if (elForm.elements[i].type=='radio' && elForm.elements[i].checked) {
					params[elName]=encodeURIComponent(elValue);
				}
				else if (elValue!='' && elForm.elements[i].type!='radio'){
					params[elName]=elValue;
				}
			}
		}
	}
	if($('add_butt_ref')){
		$('add_butt_ref').value="Ждите...";
		$('add_butt_ref').disabled=true;
	}
	if($('add_butt_ref_down')){
		$('add_butt_ref_down').value="Ждите...";
		$('add_butt_ref_down').disabled=true;
	}


	Ext.Ajax.request({
		url: elForm.action,
		success: function(response, options) {
			var res = Ext.decode(response.responseText);
			if (res.success) {
				displayRef(elForm.id.substring(5));
				elForm.reset();
				alert("Спасибо за Ваш отзыв! После прохождения модерации мы опубликуем его на сайте");
			}
			else alert('Ошибка. ' + res.message);
			if($('add_butt_ref')){
				$('add_butt_ref').value="Добавить";
				$('add_butt_ref').disabled=false;
			}
			if($('add_butt_ref_down')){
				$('add_butt_ref_down').value="Добавить";
				$('add_butt_ref_down').disabled=false;
			}
		},
		failure:  function(response, options) {
			alert('Ошибка связи. Попробуйте повторить позже.');
			if($('add_butt_ref')){
				$('add_butt_ref').value="Добавить";
				$('add_butt_ref').disabled=false;
			}
			if($('add_butt_ref_down')){
				$('add_butt_ref_down').value="Добавить";
				$('add_butt_ref_down').disabled=false;
			}
		},
		params: params
	});

	return false;
}

//function formAddOther(params) {
//	//params['video'] = encodeURIComponent($('video').value);
//	return params;
//}

function markFieldInvalid(el){
	if (el.tagName=='LABEL') {
		el.className+=' error_label';
	} else {
		el.className+=' field_error';
	}
}

function clearFieldInvalid(el){
	if (el.tagName=='LABEL') {
		el.className=el.className.replace('error_label','');
	} else {
		el.className=el.className.replace('field_error','');
	}
}


UserPhoto = function(config) {
	if (typeof config == 'object') {
		for (var prop in config) {
			this[prop] = config[prop];
		}
	}

	this.uploadedPhotos = new Array();
	for (var i = 0; i < this.maxPhotoCount; ++i) {
		this.uploadedPhotos[i] = (i >= config.loaded ? 0 : 1);
	}
};

UserPhoto.prototype.maxPhotoCount = 20;
UserPhoto.prototype.photosInRow = 4;
UserPhoto.prototype.removeUrl = '/ajax/remove_photo.php';

UserPhoto.prototype.countPhotos = function () {
	for (var i = 0; i < this.maxPhotoCount; ++i) {
		if (this.uploadedPhotos[i] == 0) {
			return i;
		}
	}
	return this.maxPhotoCount;
};


UserPhoto.prototype.getDeleteOnClickHandler = function(scope, i, unifiedid) {
	return function() {
		scope.remove(i, unifiedid);
		return false;
	};
};

UserPhoto.prototype.getDeleteOnClickHandlerForEdit = function(scope, i, unifiedid) {
	return function() {
		scope.remove(i, unifiedid, 'session only');
		return false;
	};
};

UserPhoto.prototype.getNextNodeParent = function () {
	var i = this.countPhotos();
	var newNodeParent;
	if (i == 0) {
		newNodeParent = $('downloaded-photo-tr-first');
	} else if (i % this.photosInRow == 0) {
		newNodeParent = document.createElement('TR');
		$('downloaded-photo-tr-first').parentNode.appendChild(newNodeParent);
	} else {
		newNodeParent = $('downloaded-photo-' + i).parentNode;
	}
	return newNodeParent;
};

UserPhoto.prototype.showUploadBlock = function (){
	var i = this.countPhotos();
	if ($("input-file-upload").value=='' || i == this.maxPhotoCount) {
		return false;
	}

	var origin 	= $('downloaded-photo-');
	var node 	= origin.cloneNode(true);
	var textplace= node.getElementsByTagName('IMG')[0].parentNode.parentNode;
	//var span 	= node.getElementsByTagName('SPAN')[0];
	//var input  	= node.getElementsByTagName('LABEL')[0];
	var label  	= node.getElementsByTagName('INPUT')[0];
	label.style.visibility="hidden";
	//input.style.visibility="hidden";
	//span.style.visibility="hidden";
	node.id += (i + 1);
	this.getNextNodeParent().appendChild(node);
	$('photoUploadButton').value="Ждите...";
	$('photoUploadButton').disabled=true;
	textplace.innerHTML="<div style='height:57px; font-size: 12px; font-weight: bold; color: #aaaaaa'>Загрузка...</div>";
	node.style.display = '';
	calculatePhotoWeight(i);

	return true;
};

UserPhoto.prototype.clearUploadForm = function() {
	$('input-file-upload').value='';
	$('photoUploadButton').style.display='none';
};

UserPhoto.prototype.hideUploadBlock = function() {
	var i = this.countPhotos();
	if (i == this.maxPhotoCount) {
		return false;
	}

	var block = $('downloaded-photo-' + Number(i+1));
	if(!block) return false;
	var parentNode = block.parentNode;
	$('photoUploadButton').disabled=false;
	$('photoUploadButton').value="Загрузить фото";
	parentNode.removeChild(block);
};

UserPhoto.prototype.doneUpload = function(src, width, height, tempname, unifiedid, caption) {
	var inp = $('input-file-upload');
	if (inp) {
		var parentNode = inp.parentNode;
		if (parent) {
			parentNode.removeChild(inp);
			inp = document.createElement('INPUT');
			inp.type = 'file';
			inp.name = 'photo';
			inp.id   = 'input-file-upload';
			inp.size = 16;
			inp.onchange = function(){ $('photoUploadButton').style.display='inline';};
			parentNode.appendChild(inp);

		}
	}

	var i = this.countPhotos();
	if (i == this.maxPhotoCount) {
		return false;
	}

	var origin 	= $('downloaded-photo-');
	var node 	= origin.cloneNode(true);
	var img 	= node.getElementsByTagName('IMG')[0];
	var link 	= node.getElementsByTagName('A')[0];
	//var label 	= node.getElementsByTagName('LABEL')[0];
	//var input  	= node.getElementsByTagName('INPUT')[0];
	var filename= node.getElementsByTagName('INPUT')[0]; // 1

	node.id += (i + 1);

	img.src = src;

	//label.setAttribute('for', (i + 1));
	//input.id 	+= (i + 1);
	//if (caption) {
	//	input.value = caption;
	//}
	filename.id += (i + 1);
	filename.value = tempname;

	link.onclick = this.getDeleteOnClickHandler(this, i, unifiedid);

	if (unifiedid) {
		link.setAttribute('unifiedid', unifiedid);
	}

	this.getNextNodeParent().appendChild(node);

	node.style.display = '';

	if (this.countPhotos() == this.maxPhotoCount) {
		$('downloaded-photo-form').style.display = 'none';
	}

	this.uploadedPhotos[i] = 1;
};

UserPhoto.prototype.remove = function(i, unifiedid) {
	// TODO rewrite
	var block = $('downloaded-photo-' + (i+1));
	var src = block.getElementsByTagName('IMG')[0].src;
	var parentNode = block.parentNode;

	parentNode.removeChild(block);

	var count = this.countPhotos();

	for (var j = i+1; j < count; ++j) {
		var node = $('downloaded-photo-' + (j+1));
		node.id = 'downloaded-photo-' + j;

		var link  = node.getElementsByTagName('A')[0];
		var linkUnifiedId = link.getAttribute('unifiedid');
		link.onclick = this.getDeleteOnClickHandler(this, j-1, linkUnifiedId);

		//var label = node.getElementsByTagName('LABEL')[0];
		//label.setAttribute('for', 'ad-caption-' + j);

		//		var input = node.getElementsByTagName('INPUT')[0];
		//		input.id = 'ad-caption-' + j;

		var filename = node.getElementsByTagName('INPUT')[0]; //1
		filename.id = 'filename-' + j;

		if (j % this.photosInRow == 0) {
			// Move cell to previous row
			var parentNode = node.parentNode;
			parentNode.removeChild(node);
			$('downloaded-photo-' + (j-1)).parentNode.appendChild(node);
			if (j == count - 1) {
				// Removing last empty row
				parentNode.parentNode.removeChild(parentNode);
			}
		}
	}
	this.uploadedPhotos[count-1] = 0;

	Ext.Ajax.request({
		url: this.removeUrl,
		success:  function() {
			$('downloaded-photo-form').style.display = '';
			calculatePhotoWeight(i,'rem',count);
		},
		failure:  function() {},
		params: {photo: src, id: i, unid: unifiedid, rand: (this.rand ? this.rand : 0), op: (arguments[2] ? arguments[2] : '') }
	});

	return false;
};

UserPhoto.prototype.getCaptions = function(paramName, elementPrefix) {
	elementPrefix = elementPrefix || 'ad-caption-';
	paramName = paramName || 'add-captions';
	var result = Array();
	for (var i = 0; i < this.maxPhotoCount; ++i) {
		if (this.uploadedPhotos[i] == 1 && $(elementPrefix + (i + 1))) {
			result.push(paramName + '[]=' + $F(elementPrefix + (i + 1)));
		}
	}
	return result.join('&');
};

UserPhoto.prototype.getPhotos = function(elementPrefix) {
	elementPrefix = elementPrefix || 'ad-caption-';

	var ph_count = this.countPhotos();
	var params = [];
	for (i = 0; i < ph_count; i++){
		if ($('filename-'+(i+1))){
			params['photo-' + $F('filename-'+(i+1))] = $F(elementPrefix+(i+1));
		}
	}

	return params;
};

// power sellers list

function showSendPsellerRequestForm(){
	document.getElementById('sendPsellerRequest').style.display = 'block';
	return false;
}

function hideSendPsellerRequestForm(){
	document.getElementById('sendPsellerRequest').style.display = 'none';
	return false;
}

function changePowersRegion() {
	root_path = $('root_region_path').innerHTML;
	region = $('regions').value;

	if(region.length > 0){
		if (region=='saint-petersburg'){
			setCookie2('user_region', 'saint-petersburg', dateAdd($('site_cookie_lifetime').value).toGMTString(), '/',$('site_cookie_path').value);
		}
		new_path = 'http://' + region + '.' + root_path;
	} else {
		setCookie2('user_region', '', 'Sat, 18 Apr 2009 11:04:50 GMT', '/',$('site_cookie_path').value);
		new_path = 'http://' + root_path;
	}

	window.location = new_path;
}

function psellerRequestSuccess(){
	alert('Заявка успешно отправлена');
	hideSendPsellerRequestForm();
}

function psellerRequestFailure(message){
	alert(message);
}

function showLogoBlock(){
	document.getElementById('changeLogoBlock').style.display = 'block';
	document.getElementById('changeLogoLink').style.display = 'none';
}

function sendPsellerareaContactInfoForm() {
	// validation
	var not_empty_fields = new Array();
	not_empty_fields[0] = 'title';
	not_empty_fields[1] = 'address';
	not_empty_fields[2] = 'phone';
	not_empty_fields[3] = 'contact_person';

	for(i=0; i<not_empty_fields.length; i++){
		name = not_empty_fields[i];
		if($(name).value.length == 0) {
			alert('Пожалуйста, заполните все поля формы, отмеченные красной звёздочкой');
			return false;
		}
	}

	// send form
	Ext.Ajax.request({
		form: 'psellerareaContactInfoForm',
		success: successContactInfoUpdate,
		failure: failureAlert,
		params: {action: 'pseller_contact_info'}
	});
	return false;
}


function sendPsellerareaDetailsForm() {
	Ext.Ajax.request({
		form: 'psellerareaDetailsForm',
		success: successDetailsUpdate,
		failure: failureAlert,
		params: {action: 'pseller_detail_info'}
	});
	return false;
}

function successDetailsUpdate(response, options) {
	document.getElementById('alerts').style.display = 'none';
	document.getElementById('message_panel').style.display = 'block';
	return false;
}

function submitSearchForm(){
	var form = form || $('filters');
	var basehref = '';
	var searchstring = 'search';

	if(form.action!=''){
		basehref=form.action;
	}else{
		if(window.location.href.search('/search/')!=-1){
			basehref=window.location.href.substr(0, window.location.href.search('/search/'));
		}else{
			basehref=window.location.href;
		}
	}

	for(i=0; i<form.elements.length; i++){
		if(form.elements[i].name!='' && form.elements[i].value!=''){
			searchstring+='/' + form.elements[i].name + '=' + encodeURIComponent(form.elements[i].value);
		}
	}

	searchstring+='/';
	if(searchstring=='/search/'){
		return false;
	}


	window.location=basehref + '/' + searchstring;
	return false;
}

function submitSmallSearchForm(){
	var form = form || $('small_filters');
	var basehref = '';
	var searchstring = 'search';

	if(form.action!=''){
		basehref=form.action;
	}else{
		if(window.location.href.search('/search/')!=-1){
			basehref=window.location.href.substr(0, window.location.href.search('/search/'));
		}else{
			basehref=window.location.href;
		}
	}

	for(i=0; i<form.elements.length; i++){
		if(form.elements[i].name!='' && form.elements[i].value!=''){
			searchstring+='/' + form.elements[i].name + '=' + encodeURIComponent(form.elements[i].value);
		}
	}

	searchstring+='/';
	if(searchstring=='/search/'){
		return false;
	}

    if (basehref.substr(-1) == '/') {
        window.location=basehref + searchstring;
    } else {
	window.location=basehref + '/' + searchstring;
    }
	return false;
}

// end power sellers list

// ad statictic
function showAdStatistic(){
	var uri_params = window.location.pathname.split('/');

	var ad_id = parseInt(uri_params[2]);

	if(uri_params[3] != 'statistic'){
		return false;
	}

	var create_date = parseInt($('ad_date_create').innerHTML);

	Ext.Ajax.request({
		url: '/counter/ad_statistic.php',
		success: successShowAdStatistic,
		failure: failureShowAdStatistic,
		params: {id: ad_id,
		date: create_date}
	});
}

function successShowAdStatistic(response, options) {
	var res = Ext.decode(response.responseText);
	if(res.success == true){
		displayStatisticParams(res.hits, res.day_hits);
	} else {
		displayStatisticParams('неизвестно', 'неизвестно');
	}
}

function failureShowAdStatistic() {
	displayStatisticParams('неизвестно', 'неизвестно');
}

function displayStatisticParams(hits, day_hits){
	$('ad_stat').style.display = 'block';
	$('stat_hits').innerHTML = hits;
	$('stat_day_hits').innerHTML = day_hits;
}

// end ad statistic

function checkFilterFormStyle(){
	if ($('simple-search')) {
		$filterStyle = getCookie2('filterFormStyle');
		if (!$filterStyle || $filterStyle=='') $filterFormStyle=0;
		switch($filterStyle){
			case '1':
			showMainFilters();
			break;
			case '2':
			showMainFilters();
			showMoreFilters();
			break;
		}
	}
}


function getCategoriesSelect(el) {
	$('waitMessage').style.display = '';
	Ext.Ajax.request({
		url: '/ajax/categories.php',
		success: successToGetCategoriesSelect,
		failure: failureToGetCategoriesSelect,
		params: {category: el.value}
	});
}

function successToGetCategoriesSelect(response, options) {
	var res = Ext.decode(response.responseText);
	$('waitMessage').style.display = 'none';
	if (res && res.item && res.item.title) {
		var oCategoriesNavigation = $('categoriesNavigation');
		var oCategories = $('oCategories');
		var linkEl = document.createElement('A');
		linkEl.href = '?category=' + res.item.prev_uri;
		linkEl.onclick = function() { replaceAnchorBySelectSelect(this, res.item.prev_uri); return false; };
		linkEl.appendChild(document.createTextNode(res.item.title));
		oCategoriesNavigation.appendChild(linkEl);
		linkEl = document.createTextNode(' ');
		oCategoriesNavigation.appendChild(linkEl);

		if (res.categories.length>0){
			var linkEl = document.createElement('SPAN');
			linkEl.className="blue";
			linkEl.appendChild(document.createTextNode('»'));
			oCategoriesNavigation.appendChild(linkEl);
			linkEl = document.createTextNode(' ');
			oCategoriesNavigation.appendChild(linkEl);

			updateCategories(res.categories);
		} else {
			oCategories.style.display = 'none';
			//			return true;
		}
		$('id_category').value='classified/'+res.item.uri; //Кто здесь??

	} else {
		alert('Ошибка связи. Попробуйте повторить позже.');
	}
}

function failureToGetCategoriesSelect() {
	$('waitMessage').style.display = 'none';
	alert('Ошибка связи. Попробуйте повторить позже.');
}

function replaceAnchorBySelectSelect(_this) {
	//wizardSelectCategory();

	if (arguments.length > 0) {
		var temp = arguments[1]; //for search alert editing
	}else{
		var temp = getValueFromURL('region',_this.href);
	}

	var message = $('waitMessage');
	var oCategories = $('oCategories');
	var parentNode = _this.parentNode;
	var el = {};
	while (el = _this.nextSibling) {
		parentNode.removeChild(el);
	}
	Ext.Ajax.request({
		url: '/ajax/categories.php',
		success: function(response, options) {
			var res = Ext.decode(response.responseText);
			if (res && res.categories && res.categories.length>0) {
				updateCategories(res.categories);
				$('id_category').value='';
			} else {
				alert('Ошибка связи. Попробуйте повторить позже.');
			}
		},
		failure: failureToGetCategories,
		params: {category: temp}
	});
	parentNode.removeChild(_this);
	oCategories.style.display = '';

	return false;
}

function checkFilterRestore(){
	var chSymbol = ',';
	formsIds = new Array('filters1','filters2','subscriptionForm');

	for (k=0; k<formsIds.length; k++) {
		if (el=$(formsIds[k])){
			if (el.elements){
				for (i=0; i<el.elements.length; i++){
					elName=el.elements[i].name;
					if (elName=='make' && $('auto_model')) {
						if (typeof(make_type) === "undefined") {
							// For models of passenger cars only
							loadModel('auto_model',el.elements[i],$('sp_savedmodel').value,1, 1);
						} else {
							loadModel('auto_model',el.elements[i],$('sp_savedmodel').value,1, 1, make_type);
						}
					} else if (elName=='currency'){
						checkCurrency(el.elements[i]);
					} else if (elName.indexOf('sp_')==0) {
						elValue=el.elements[i].value;
						/* for checkboxes */
						j=1;
						testElName='ch_'+elName.replace('sp_','')+'_'+j;
						while (el[testElName] && el[testElName].type=='checkbox') {
							if((new RegExp("(^|,)"+el[testElName].value+"(,|$)")).test(elValue+chSymbol)) {
								//if ((elValue+chSymbol).indexOf(el[testElName].value)>-1) {
								el[testElName].checked=true;
							}
							j++;
							testElName='ch_'+elName.replace('sp_','')+'_'+j;
						}
						/* --- */

					}
				}
			}
		}
	}
}

function sh_phone(chk, div) {
	if(chk.checked) elShow(div);
	else elHide(div);
}

function deleteAd(id) {
	if(confirm('Вы действительно хотите удалить объявление?')) goTo('/ajax/deleteAd.php?id='+id);
}
function editAd(id) {
	goTo('/editAdvert/'+id+'/');
}
function utf8_encode ( str_data ) { //Encodes string to UTF-8

	str_data = str_data.replace(/\r\n/g,"\n");
	var utftext = "";

	for (var n = 0; n < str_data.length; n++) {
		var c = str_data.charCodeAt(n);
		if (c < 128) {
			utftext += String.fromCharCode(c);
		} else if((c > 127) && (c < 2048)) {
			utftext += String.fromCharCode((c >> 6) | 192);
			utftext += String.fromCharCode((c & 63) | 128);
		} else {
			utftext += String.fromCharCode((c >> 12) | 224);
			utftext += String.fromCharCode(((c >> 6) & 63) | 128);
			utftext += String.fromCharCode((c & 63) | 128);
		}
	}

	return utftext;
}

function crc32 ( str ) {
	// http://kevin.vanzonneveld.net
	// +   original by: Webtoolkit.info (http://www.webtoolkit.info/)
	// +   improved by: T0bsn
	// -    depends on: utf8_encode
	// *     example 1: crc32('Kevin van Zonneveld');
	// *     returns 1: 1249991249

	var table = "00000000 77073096 EE0E612C 990951BA 076DC419 706AF48F E963A535 9E6495A3 0EDB8832 79DCB8A4 E0D5E91E 97D2D988 09B64C2B 7EB17CBD E7B82D07 90BF1D91 1DB71064 6AB020F2 F3B97148 84BE41DE 1ADAD47D 6DDDE4EB F4D4B551 83D385C7 136C9856 646BA8C0 FD62F97A 8A65C9EC 14015C4F 63066CD9 FA0F3D63 8D080DF5 3B6E20C8 4C69105E D56041E4 A2677172 3C03E4D1 4B04D447 D20D85FD A50AB56B 35B5A8FA 42B2986C DBBBC9D6 ACBCF940 32D86CE3 45DF5C75 DCD60DCF ABD13D59 26D930AC 51DE003A C8D75180 BFD06116 21B4F4B5 56B3C423 CFBA9599 B8BDA50F 2802B89E 5F058808 C60CD9B2 B10BE924 2F6F7C87 58684C11 C1611DAB B6662D3D 76DC4190 01DB7106 98D220BC EFD5102A 71B18589 06B6B51F 9FBFE4A5 E8B8D433 7807C9A2 0F00F934 9609A88E E10E9818 7F6A0DBB 086D3D2D 91646C97 E6635C01 6B6B51F4 1C6C6162 856530D8 F262004E 6C0695ED 1B01A57B 8208F4C1 F50FC457 65B0D9C6 12B7E950 8BBEB8EA FCB9887C 62DD1DDF 15DA2D49 8CD37CF3 FBD44C65 4DB26158 3AB551CE A3BC0074 D4BB30E2 4ADFA541 3DD895D7 A4D1C46D D3D6F4FB 4369E96A 346ED9FC AD678846 DA60B8D0 44042D73 33031DE5 AA0A4C5F DD0D7CC9 5005713C 270241AA BE0B1010 C90C2086 5768B525 206F85B3 B966D409 CE61E49F 5EDEF90E 29D9C998 B0D09822 C7D7A8B4 59B33D17 2EB40D81 B7BD5C3B C0BA6CAD EDB88320 9ABFB3B6 03B6E20C 74B1D29A EAD54739 9DD277AF 04DB2615 73DC1683 E3630B12 94643B84 0D6D6A3E 7A6A5AA8 E40ECF0B 9309FF9D 0A00AE27 7D079EB1 F00F9344 8708A3D2 1E01F268 6906C2FE F762575D 806567CB 196C3671 6E6B06E7 FED41B76 89D32BE0 10DA7A5A 67DD4ACC F9B9DF6F 8EBEEFF9 17B7BE43 60B08ED5 D6D6A3E8 A1D1937E 38D8C2C4 4FDFF252 D1BB67F1 A6BC5767 3FB506DD 48B2364B D80D2BDA AF0A1B4C 36034AF6 41047A60 DF60EFC3 A867DF55 316E8EEF 4669BE79 CB61B38C BC66831A 256FD2A0 5268E236 CC0C7795 BB0B4703 220216B9 5505262F C5BA3BBE B2BD0B28 2BB45A92 5CB36A04 C2D7FFA7 B5D0CF31 2CD99E8B 5BDEAE1D 9B64C2B0 EC63F226 756AA39C 026D930A 9C0906A9 EB0E363F 72076785 05005713 95BF4A82 E2B87A14 7BB12BAE 0CB61B38 92D28E9B E5D5BE0D 7CDCEFB7 0BDBDF21 86D3D2D4 F1D4E242 68DDB3F8 1FDA836E 81BE16CD F6B9265B 6FB077E1 18B74777 88085AE6 FF0F6A70 66063BCA 11010B5C 8F659EFF F862AE69 616BFFD3 166CCF45 A00AE278 D70DD2EE 4E048354 3903B3C2 A7672661 D06016F7 4969474D 3E6E77DB AED16A4A D9D65ADC 40DF0B66 37D83BF0 A9BCAE53 DEBB9EC5 47B2CF7F 30B5FFE9 BDBDF21C CABAC28A 53B39330 24B4A3A6 BAD03605 CDD70693 54DE5729 23D967BF B3667A2E C4614AB8 5D681B02 2A6F2B94 B40BBE37 C30C8EA1 5A05DF1B 2D02EF8D";

	var crc = 0;
	var x = 0;
	var y = 0;
	str = utf8_encode(str);

	crc = crc ^ (-1);
	for( var i = 0, iTop = str.length; i < iTop; i++ ) {
		y = ( crc ^ str.charCodeAt( i ) ) & 0xFF;
		x = "0x" + table.substr( y * 9, 8 );
		crc = ( crc >>> 8 ) ^ Number(x);
	}

	var N = parseFloat(crc ^ (-1));
	if (N < 0) return (4294967296.0 + N);
	return N;
}

function loadModel(id,source,act,withany, crc32values, cfg){
	var sendme = {name: source.options[source.selectedIndex].text,withany: (withany?1:0)};
	if(cfg) sendme.cfg = cfg;
	Ext.Ajax.request({
		url: '/ajax/load_auto_models.php',
		success: function(response, options) {
			var res = Ext.decode(response.responseText);
            for (var i = res.models.length; i > 0; i--) {
                res.models[i] = res.models[i-1];
            }
            res.models[0]='';

            if (res && res.models) {


				var select2=document.getElementById(id);
                if (window.navigator.appName.indexOf('icros')==-1) select2.innerHTML="";
                else for (var i=0;i<select2.children.length;i++) select2.removeChild(select2.children[i]);


				for (var i = 0; i < res.models.length; i++) {

					if(res.models[i] == '') continue;

					el = document.createElement('OPTION');
					if(crc32values){
						el.value = res.models[i]!='-' ? crc32(res.models[i]) : '';
					}else{
						el.value = res.models[i]!='-' ? res.models[i] : '';
					}
					if (act==res.models[i] || act==crc32(res.models[i])) {
						el.selected='selected';
					}
					el.innerHTML = res.models[i];
					select2.appendChild(el);
				}
			} else {
				//alert('Ошибка связи. Попробуйте повторить позже.');
			}
		},
		failure: function(response, options) {
			//alert('Ошибка связи. Попробуйте повторить позже.');
		},
		//params: {name: source.value,withany: (withany?1:0)}
		params: sendme
	});
}

Ext.onReady(function(){
	checkFilterFormStyle();
	checkFilterRestore();
	window.oldClientWidth = document.body.clientWidth;
	var handler = function () {
		if (window.firstLoadEvent === undefined) {
			window.firstLoadEvent = true;
		}
	};
	htmlblocks();
	// Workaround for IE6;
	if (Ext.isIE6) {
		//var dt = new Ext.util.DelayedTask(handler, window);
		//dt.delay(10000);
		document.body.onload = handler;
	} else {
		handler();
	}
});

Ext.EventManager.on(window, 'load', function(){
	// Workaround for IE7
	htmlblocks();
	if (window.firstLoadEvent === undefined) {
		window.firstLoadEvent = true;
	}
	if(window.console && window.console.firebug){
		//			alert('Для корректной и быстрой работы сайта отключите Firebug.');
	}
});


function formAlertSubmit(elForm, btn){
	flagSend=true;
	if (necessaryFields && necessaryFields.length>0){
		for (i=0; i<necessaryFields.length; i++) {
			if ($('id_'+necessaryFields[i])) {
				el=$('id_'+necessaryFields[i]);
				if (necessaryFields[i] == 'email' && !isEmail(el.value)){
					markFieldInvalid(el.parentNode);
					flagSend=false;
				}
				if (el.value=='') {
					markFieldInvalid(el.parentNode);
					flagSend=false;
				}
			}
		}
	}
	if (flagSend){
		var eqSymbol = '=';
		var params = new Array();
		if (elForm.elements){
			for (i=0; i<elForm.elements.length; i++){
				elName=elForm.elements[i].name;
				if (elName && elName!='') {
					elValue=elForm.elements[i].value;
					if (elForm.elements[i].type=='checkbox') {
						elValue=(elForm.elements[i].checked ? 1 : 0);
					}else if (elForm.elements[i].type=='radio'){
						elValue=(elForm.elements[i].checked ? elForm.elements[i].value : '');
					}
					if (elValue!=''){
						params[elName]=encodeURIComponent(elValue);
					}
				}
			}
		}

		var oldValue = btn.value;
		btn.value = 'Ждите';
		btn.disabled = true;
		Ext.get(btn).parent('div').replaceClass('btn-a', 'btn-b');

		Ext.Ajax.request({
			url: elForm.action,
			success: function(response, options) {
				var res = Ext.decode(response.responseText);
				if (res && res.alert_id) {
					goTo(res.url_togo);
				} else {
					alert('Ошибка связи. Попробуйте повторить позже.');
					btn.value = oldValue;
					btn.disabled = false;
					Ext.get(btn).parent('div').replaceClass('btn-b', 'btn-a');
				}
			},
			failure:  function(response, options) {
				alert('Ошибка связи. Попробуйте повторить позже.');
				btn.value = oldValue;
				btn.disabled = false;
				Ext.get(btn).parent('div').replaceClass('btn-b', 'btn-a');
			},
			params: params
		});
	}

	return false;
}

function deleteAlerts(){
	var del_sa = Ext.query('input:checked[class="sa_chkbox"]');

	if (!del_sa.length){
		alert('Подписки не выбраны');
		return;
	}

	if (!confirm('Вы уверены, что хотите удалить выбранные подписки?')) return;

	var ids = '';
	for (i=0; i<del_sa.length; i++){
		if(del_sa[i].id) {
			ids += del_sa[i].id.substring(3) + ',';
		}
	}

	Ext.Ajax.request({
		url: '/ajax/searchalert.php',
		success: function(response, options) {
			goTo('/myadverts/alerts/');
		},
		failure:  function(response, options) {
			alert('Ошибка связи. Попробуйте повторить позже.');
			goTo('/myadverts/alerts/');
		},
		params: {'ids': ids, 'op': 'deleteall'}
	});

}

function checkAll(className){
	var a = Ext.query('input[class="' + className + '"]');
	Ext.each(a, function (item, index) {item.checked = true;});
}


function fastSearch(form, attr, value){
	var form = form || $('filters');
	var basehref = '';
	basehref=form.action.replace('http://' + document.domain, '');
	if(value != ''){
		document.location = basehref + '/search/'+attr+'=' + value;
	}else{
		document.location = basehref + '/';
	}
	return false;
}

function fastSearchExt(basehref, attr, value){
	if(value != ''){
		document.location = basehref + 'search/'+attr+'=' + value;
	}else{
		document.location = basehref + '';
	}
	return false;
}

function getAdAddStatus(reg) {
	if(!Ext.get('categoriesNavigation')) return;

	Ext.Ajax.request({
		url: '/ajax/categories.php',
		success: function(response, options) {
			var res = Ext.decode(response.responseText);
			var p = Ext.get('categoriesNavigation').parent();
			var ul = p.prev('ul'); if(ul) ul.remove();
			p.insertHtml('beforeBegin',res.limits);
			if (res.isaddpp != 0){
				if ($('pp-addr-fields')) $('pp-addr-fields').style.display = 'block';
			}else{
				if ($('pp-addr-fields')){
					$('pp-addr-fields').style.display = 'none';
					Ext.each(Ext.get('pp-addr-fields').query('input'),function(a){a.value='';});
				}
			}
		},
		params: {'isinpackage': 1, 'category': getValueFromURL('category', window.location.href), 'region': reg}
	});
}
function show_metromap(){
	elShow('metromap');
	elHide('block_filter_region');
}
function hide_metromap(){
	elHide('metromap');
}
function stopPropagation(){
	if (arguments[0]){
		e = arguments[0];
	}else{
		e = window.event;
	}
	if (!e) return;
	e.cancelBubble = true;
	if (e.stopPropagation) e.stopPropagation();
}

// swicth visability of neighbours div in appartment sale filter
function switchNeighbours() {
	var lbl = $('lbl-neighbours');
	var input = $('input-neighbours');

	if('block' == lbl.style.display) lbl.style.display = 'none';
	else lbl.style.display = 'block';

	if('block' == input.style.display){
		input.style.display = 'none';
		$('filter-neighbours').value = '';
	} else {
		input.style.display = 'block';
	}
}

//function popup(){
//	open("","Test","width=600,height=500,scrollbars=1");
//}
var divs;
var x;
var aaa;

function cont_show_child(elem){
	if (aaa){clearTimeout(aaa); aaa = false;}
}

function show_child(elem) {
	if (aaa){clearTimeout(aaa); aaa = false;}
	divs = $('maintrack').getElementsByTagName ("div");
	for (var x=0; x<divs.length; x++){
		if (divs[x].className == "popup" && divs[x].style.display != "none"){divs[x].style.display = "none";}
	}
	divs = elem.parentNode.getElementsByTagName ("div");
	for (var x=0; x<divs.length; x++){
		if (divs[x].className == "popup" && divs[x].style.display != "block"){
			divs[x].style.display = "block";
			iframes = elem.parentNode.getElementsByTagName ("iframe");/*IE6*/
			tables = elem.parentNode.getElementsByTagName ("table");/*IE6*/
			if (!tables[0].style.width){tables[0].style.width = divs[x].offsetWidth+15+'px';}/*IE6*/
			iframes[0].style.height = divs[x].offsetHeight-20+'px';/*IE6*/
			iframes[0].style.width = divs[x].offsetWidth-11+'px';/*IE6*/
		}
	}
	var spans = document.getElementsByTagName ("span");
	for (var x = 0; x < spans.length; x++){
		if (spans[x].className == 'arrow-down'){
			if (spans[x].parentNode.parentNode.parentNode.parentNode.parentNode.className == "popup"){spans[x].style.marginLeft = elem.offsetWidth-12+'px';}
		}
	}
}

function hide_el(xx){
	divs = $('maintrack').getElementsByTagName ("div");
	divs[xx].style.display = "none";
}

function hide_child(elem) {
	divs = $('maintrack').getElementsByTagName ("div");
	for (var x=0; x<divs.length; x++){
		if (divs[x].className == "popup" && divs[x].style.display == "block"){
			aaa = setTimeout ("hide_el('"+x+"');", 500);}
	}
}

//switch currency in price field
function checkCurrency(obj){
	if (obj.value == 'RUR') n = 0;
	else if (obj.value == 'USD') n = 1;
	else if (obj.value == 'EUR') n = 2;
	setPrices(n);
}

function setPrices(currency){
	if(!(priceList = $('ulPrice'))) return;
	var k=0;
	for (var i=0; i<priceList.childNodes.length; i++){
		if(priceList.childNodes[i].tagName == 'LI'){
			priceItem = priceList.childNodes[i];
			for (var j=0; j<priceItem.childNodes.length; j++){
				if(priceItem.childNodes[j].tagName == 'A'){
					priceItem.childNodes[j].innerHTML = price[k][currency];
					k++;
				}
			}
		}
	}
}
function htmlblocks(){
	//var timestart = new Date();
	var blocks = Ext.query('div.htmlbl{display!=none}');
	var height = 0;
	var num = blocks.length;
	for (var x = 0; x < num; x++) {
		blocks[x].style.clear = "";
		blocks[x].style.height = "";
		blocks[x].style.border = "";
		if (x < Math.floor(num/3)*3 && num > 3) {
			blocks[x].style.borderBottom = "1px solid #ececec";
		}
		if (x % 3 != 2) {
			blocks[x].style.borderRight = "1px solid #ececec";
		}
		if (x % 3 == 0){
			blocks[x].style.clear = "both";
			if (x > 0) {
				htmlblocks_height(height, x, blocks);
			}
			height = 0;
		}
		if (height < blocks[x].offsetHeight){height = blocks[x].offsetHeight;}
	}
	htmlblocks_height(height, x, blocks);
	//var timeend = new Date();
	//console.log("htmlblocks %d", timeend - timestart);
}
function htmlblocks_height(height, y, blocks){
	var start = 1;
	var z = start;
	if (y > 3) {start = y-2;}
	if (y % 3 != 0){start = y;}
	for (var x = 0; x < blocks.length; x++){
		if (z >= start && z <= y){blocks[x].style.height = height+10+'px';}
		z++;
	}
}
function searchByPhone(form){
	if ($('search-phone')) {
		phone=$('search-phone').value;
		if (phone!=''){
			var reg=/\D/g;
			phone=phone.replace(reg, " ");
			document.location=form.action+'keywords='+phone+'/';
		}
	}
	return false;
}
window.onresize = function (e){
	if (window.oldClientWidth != document.body.clientWidth) {
		window.oldClientWidth = document.body.clientWidth;
		htmlblocks();
	}
	init();
};

//show multiply select of powersellers when user choose 'Internet-partnery' item in search filter
function sourceFilterSelect(element){
	if (3 == element.value){
		elShow('choosePowersellers');
	} else {
		elHide('choosePowersellers');
	}
}
/*=============SCROLL TABLE=============================*/
Scroll = function (scroller, scroller_bar, menu)
{
	this.canDrag = false;
	this.prepared = false;

	this.shift_x;
	this.delta;

	this.scroller = scroller;
	this.scrollerBar = scroller_bar;
	this.menu = menu;

	this.scrollerStartShift;
	this.menuStartShift;
	this.menuWidth = width;

	this.scrollerTrackWidth = this.menuWidth - 33;
	this.menuTrackWidth;

	this.scrollerWidth;
	this.step;

	this.dontmove = false;

	this.a = false;

	this.prepare = function()
	{
		if(get(this.scroller) && get(this.menu))
		{
			this.scroller = get(this.scroller);
			this.scrollerBar = get(this.scroller_bar);
			this.menu = get(this.menu);
			this.scrollerStartShift = parseInt(this.scroller.style.marginLeft);
			this.menuStartShift = parseInt(this.menu.style.marginLeft);

			this.menuTrackWidth = this.menu.offsetWidth + this.menuStartShift;
			if (width == this.menuTrackWidth){get('scroll-bar').style.display='none';}
			else {get('scroll-bar').style.display='block';}
			this.scrollerWidth = Math.round( (this.menuWidth * this.scrollerTrackWidth) / this.menuTrackWidth );

			// 8 px - ширина стрелки => минимальная ширина скроллера 16px
			this.scrollerWidth = (this.scrollerWidth < 16) ?  16 : this.scrollerWidth;

			// максимальная ширина скроллера - ширина трэка
			this.scrollerWidth = (this.scrollerWidth > this.scrollerTrackWidth) ?  this.scrollerTrackWidth : this.scrollerWidth;

			// устанавливаем ширину скроллера
			this.scroller.style.width = this.scrollerWidth + "px";

			// теперь принимаем за скроллер точку (его левую границу), все расчеты будем производить относительно нее
			// задаем ширину трэка скроллера и меню
			this.scrollerTrackWidth -= this.scrollerWidth;
			this.menuTrackWidth -= this.menuWidth;

			// рассчитываем коэффициэнт
			this.delta = this.menuTrackWidth / this.scrollerTrackWidth;

			this.prepared = true;
		}
		return false;
	};

	this.fixForBrowsers = function(event)
	{
		if (!event)
		{
			// For IE.
			event = window.event;
		}
		if(event.stopPropagation) event.stopPropagation();
		else event.cancelBubble = true;
		if(event.preventDefault) event.preventDefault();
		else event.returnValue = false;
	};

	this.setStep = function()
	{
		//step = Math.round(scrollerWidth / 3 * 2);
		this.step = 20;
	};

	this.setPosition = function(newPosition)
	{
		if(newPosition <= this.scrollerTrackWidth + this.scrollerStartShift && newPosition >= this.scrollerStartShift)
		{
			this.scroller.style.marginLeft = newPosition + "px";
		}
		else
		{
			if(newPosition >= this.scrollerTrackWidth + this.scrollerStartShift)
			{
				this.scroller.style.marginLeft = this.scrollerTrackWidth + this.scrollerStartShift + "px";
			}
			if(newPosition < this.scrollerStartShift)
			{
				this.scroller.style.marginLeft = this.scrollerStartShift + "px";
			}
		}
		this.menu.style.marginLeft = Math.round( (parseInt(this.scroller.style.marginLeft) - this.scrollerStartShift) * this.delta * (-1) ) + this.menuStartShift + "px";
		return false;
	};

	this.drag = function(event)
	{
		if (!event)
		{
			// For IE.
			event = window.event;
		}
		if (this.prepared)
		{
			this.canDrag = true;
			this.shift_x = event.clientX - parseInt(this.scroller.style.marginLeft);
			this.fixForBrowsers(event);
		}
		return false;
	};

	this.movescroller = function(event)
	{
		if (!event)
		{
			// For IE.
			event = window.event;
		}
		if (this.prepared && !this.dontmove)
		{
			this.setStep();
			var clickX = event.layerX ? event.layerX : event.offsetX;
			var currentPosition = parseInt(this.scroller.style.marginLeft);
			var i = (clickX > currentPosition) ? 1 : -1;
			var newPosition = 2*i*this.step + parseInt(this.scroller.style.marginLeft);
			this.setPosition(newPosition);
			this.fixForBrowsers(event);
		}
		else
		{
			this.dontmove = false;
		}
		return false;
	};

	this.move = function(event)
	{
		if (!event)
		{
			// For IE.
			event = window.event;
		}
		if (this.prepared && this.canDrag)
		{
			this.setPosition(event.clientX-this.shift_x);
			this.fixForBrowsers(event);
		}
		return false;
	};

	this.drop = function()
	{
		this.canDrag=false;
	};

	this.scrollerClickHandler = function()
	{
		this.dontmove=true;
	};

	this.handle = function(delta, event)
	{
		if (!event)
		{
			// For IE.
			event = window.event;
		}
		var i = (delta < 0) ? 1 : -1;
		this.setStep();
		var currentPosition = parseInt(this.scroller.style.marginLeft);
		var newPosition = i*this.step + currentPosition;
		this.setPosition(newPosition);
		this.fixForBrowsers(event);
	};

	this.cancelWheelAction = function(event)
	{
		/*
		Отменяем действие колеса
		*/
		if (!event)
		{
			// For IE.
			event = window.event;
		}
		if (event.preventDefault)
		{
			event.preventDefault();
		}
		event.returnValue = false;
	};

	this.wheel = function(event)
	{
		var delta = 0;
		if (!event)
		{
			// For IE.
			event = window.event;
		}
		if (event.wheelDelta)
		{
			// IE/Opera.
			delta = event.wheelDelta/120;

			// В Opera 9, значение delta не отличается по знаку от значения в IE.
			if (window.opera)
			{
				delta = delta;
			}
		}
		else if (event.detail)
		{
			/*
			Заточка под Mozilla
			В Mozilla, значение delta отличается по знаку от значения в IE.
			Обычно, delta умножается на 3.
			*/
			delta = -event.detail/3;
		}
		/*
		Если delta отлична от 0 - юзаем ее
		Если скроллить вверх, то delta > 0
		Если скролить вниз - delta < 0
		*/
		if (delta)
		{
			this.handle(delta, event);
			this.cancelWheelAction(event);
			this.fixForBrowsers(event);
			return false;
		}
	};
};

function get(id)
{
	return document.getElementById(id);
}
function handleOnMouseUp(event)
{
	first.drop(event);
}
function handleOnMouseMove(event)
{
	first.move(event);
}

// first
function handleOnClickBarFirst(event)
{
	first.movescroller(event);
}
function handleOnMouseDownFirst(event)
{
	first.drag(event);
}
function handleOnClickFirst(event)
{
	first.scrollerClickHandler(event);
}
function handleOnMouseWheelFirst(event)
{
	first.wheel(event);
}

//third
function init(){
	if (get('adListTable')){
		get('adListTable').style.marginLeft = 0;
		var browserName=navigator.appName;
		var s_top = self.pageYOffset ||
		(document.documentElement && document.documentElement.scrollTop) ||
		(document.body && document.body.scrollTop);

		var scroller = get('scroller');
		if(!scroller) return;

		if (browserName == 'Microsoft Internet Explorer'){
			//Если IE
			scroller.style.marginLeft = 0;
			get('scroll-bar').style.top = document.documentElement.clientHeight + s_top + 20+'px';
		}
		else {scroller.style.marginLeft = 17+'px';}

		width = document.getElementById ('scroll-table').offsetWidth;
		get('scroll-bar').style.width = width+'px';

		first = new Scroll('scroller', 'scroller_bar', 'adListTable');
		first.prepare();

		document.onmousemove = handleOnMouseMove;
		window.onmouseup = handleOnMouseUp;
		get('scroller_bar').onclick = handleOnClickBarFirst;
		scroller.onmousedown = handleOnMouseDownFirst;
		scroller.onmouseup = handleOnMouseUp;
		scroller.onclick = handleOnClickFirst;

		if (browserName != 'Microsoft Internet Explorer' && navigator.appVersion.indexOf('MSIE 6.0') > -1){
			//Если не IE
			if (s_top+document.documentElement.clientHeight >= (get('scroll-table').offsetTop+get('scroll-table').clientHeight)){get('scroll-bar').style.position='absolute'; get('scroll-bar').style.top = get('scroll-table').offsetTop+get('scroll-table').clientHeight+'px';}
			if (s_top+document.documentElement.clientHeight < (get('scroll-table').offsetTop+get('scroll-table').clientHeight)){get('scroll-bar').style.position='fixed'; get('scroll-bar').style.top = 'auto';}
			if (document.documentElement.clientHeight+s_top <= get('scroll-table').offsetTop){get('scroll-bar').style.position='absolute'; get('scroll-bar').style.top = get('scroll-table').offsetTop;}
		}
	}
}
window.onscroll = function(){
	if (get('scroll-bar')){
		var browserName=navigator.appName;
		var s_top = self.pageYOffset ||
		(document.documentElement && document.documentElement.scrollTop) ||
		(document.body && document.body.scrollTop);

		if (browserName == 'Microsoft Internet Explorer' && navigator.appVersion.indexOf('MSIE 6.0') > -1){
			//Если IE
			get('scroll-bar').style.top = document.documentElement.clientHeight + s_top - 20+'px';
		}
		if (browserName == 'Microsoft Internet Explorer'){
			//Если IE
			if (navigator.appVersion.indexOf('MSIE 6.0') > -1){
				if (s_top+document.documentElement.clientHeight-130 >= (get('scroll-table').offsetTop+get('scroll-table').clientHeight)){get('scroll-bar').style.position='absolute'; get('scroll-bar').style.top = get('scroll-table').offsetTop+get('scroll-table').clientHeight+130+'px';}
				if (s_top+document.documentElement.clientHeight-130 < get('scroll-table').offsetTop){get('scroll-bar').style.position='absolute'; get('scroll-bar').style.top = get('scroll-table').offsetTop+130+'px';}
			}
			else {
				if (s_top+document.documentElement.clientHeight >= (get('scroll-table').offsetTop+get('scroll-table').clientHeight)){get('scroll-bar').style.position='absolute'; get('scroll-bar').style.top = get('scroll-table').offsetTop+get('scroll-table').clientHeight+150+'px';}
				if (s_top+document.documentElement.clientHeight-160 < (get('scroll-table').offsetTop+get('scroll-table').clientHeight)){get('scroll-bar').style.position='fixed'; get('scroll-bar').style.top = 'auto';}
				if (document.documentElement.clientHeight+s_top-130 < get('scroll-table').offsetTop){get('scroll-bar').style.position='absolute'; get('scroll-bar').style.top = get('scroll-table').offsetTop+130+'px';}
			}
		}
		else {
			if (s_top+document.documentElement.clientHeight >= (get('scroll-table').offsetTop+get('scroll-table').clientHeight)){get('scroll-bar').style.position='absolute'; get('scroll-bar').style.top = get('scroll-table').offsetTop+get('scroll-table').clientHeight+'px';}
			if (s_top+document.documentElement.clientHeight < (get('scroll-table').offsetTop+get('scroll-table').clientHeight)){get('scroll-bar').style.position='fixed'; get('scroll-bar').style.top = 'auto';}
			if (document.documentElement.clientHeight+s_top-80 <= get('scroll-table').offsetTop){get('scroll-bar').style.position='absolute'; get('scroll-bar').style.top = get('scroll-table').offsetTop;}
		}
	}
};
var width;
var first;
/*========================================================*/

function filtersSourcefromChangeCallback(e){
	var list = $('filter_psellers');

	if (list){
		if (this[this.selectedIndex].value == 3){
			//is psellers source selected
			list.style.display='block';
			if (!list.isready){
				Ext.Ajax.request({
					url: '/ajax/pseller_list.php',
					success: function(response,options){
						var res = Ext.decode(response.responseText);
						if (res.list){
							list.removeChild(list.options[0]);
							for (var i=0;i<res.list.length;i++){
								var optn = document.createElement("option");
								optn.text = res.list[i].title;
								optn.value = res.list[i].user_id;
								optn.selected = res.list[i].selected;
								try {
									list.add(optn, null);
								}
								catch (ex) {
									list.add(optn);
								}
							}
						}
						list.isready = true;
					},
					failure: function(){},
					headers: {},
					params: {
						current_value: list.getAttribute('current_value'),
						location: window.location.href
					}
				});
			}
		}else{
			list.selectedIndex=-1;
			list.style.display='none';
		}

	}
}

function base64_decode( data ) {
	// http://kevin.vanzonneveld.net
	// +   original by: Tyler Akins (http://rumkin.com)
	// +   improved by: Thunder.m
	// +      input by: Aman Gupta
	// +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
	// +   bugfixed by: Onno Marsman
	// -    depends on: utf8_decode
	// *     example 1: base64_decode('S2V2aW4gdmFuIFpvbm5ldmVsZA==');
	// *     returns 1: 'Kevin van Zonneveld'

	// mozilla has this native
	// - but breaks in 2.0.0.12!
	//if (typeof window['btoa'] == 'function') {
	//    return btoa(data);
	//}

	var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
	var o1, o2, o3, h1, h2, h3, h4, bits, i = ac = 0, dec = "", tmp_arr = [];

	data += '';

	do {  // unpack four hexets into three octets using index points in b64
		h1 = b64.indexOf(data.charAt(i++));
		h2 = b64.indexOf(data.charAt(i++));
		h3 = b64.indexOf(data.charAt(i++));
		h4 = b64.indexOf(data.charAt(i++));

		bits = h1<<18 | h2<<12 | h3<<6 | h4;

		o1 = bits>>16 & 0xff;
		o2 = bits>>8 & 0xff;
		o3 = bits & 0xff;

		if (h3 == 64) {
			tmp_arr[ac++] = String.fromCharCode(o1);
		} else if (h4 == 64) {
			tmp_arr[ac++] = String.fromCharCode(o1, o2);
		} else {
			tmp_arr[ac++] = String.fromCharCode(o1, o2, o3);
		}
	} while (i < data.length);

	dec = tmp_arr.join('');
	//dec = utf8_decode(dec);

	return dec;
}

function getOkrugList() {
	//ЦАО САО СВАО ВАО ЮВАО ЮАО ЮЗАО ЗАО СЗАО
	var regions = [202,199,200,197,204, 203,205,198,201];
	return regions;
}
function getOkrugs(okrug) {
	var SIR = new Array();
	SIR[0] = new Array(95, 107, 138, 134, 71, 66, 16, 72, 18, 170, 15, 70, 48, 94, 116, 179, 151, 109, 51, 146, 115, 131, 73, 158, 88, 139, 124, 187, 166, 80, 92, 159, 135, 185, 147, 11, 74, 7, 22, 26, 128, 164, 104, 63, 125, 160, 113, 85, 76, 168, 186, 156, 182, 152);
	SIR[1] = new Array(137, 39, 40, 148, 12, 49, 17, 127, 50, 163, 121);
	SIR[2] = new Array(9, 21, 112, 38, 141, 8, 37, 27, 142, 13, 93);
	SIR[3] = new Array(173, 183, 130, 149, 192, 145, 118, 56, 119, 190, 188, 120, 102);
	SIR[4] = new Array(4, 41, 53, 64, 77, 161, 140, 44, 122, 42, 87, 90, 31);
	SIR[5] = new Array(189, 167, 98, 99, 36, 61, 65, 5, 184, 194, 129, 171, 10, 58, 181, 111, 52, 69);
	SIR[6] = new Array(32, 172, 28, 174, 175, 29, 25, 196, 162, 67, 19, 100, 143, 60, 57, 108, 83, 6, 132);
	SIR[7] = new Array(154, 75, 97, 78, 123, 177, 14, 178, 81, 155, 62, 117, 43, 176, 193, 133);
	SIR[8] = new Array(126, 157, 169, 191, 110);
	return SIR[okrug];
}

function createOption(select,id,value,act) {
	el = document.createElement('OPTION');
	el.value = id;
	el.innerHTML = value;
	if(id==act)	el.selected='selected';
	select.appendChild(el);
}
function loadCity(id,source,act){
	var sendme = {id: source.options[source.selectedIndex].value};

	Ext.Ajax.request({
		url: '/ajax/regionsForId.php',
		success: function(response, options) {
			var res = Ext.decode(response.responseText);
			if (res && res.regions) {
				select=$(id);
				select.innerHTML = '';

				createOption(select, '', '-');
				for (var i = 0; i < res.regions.length; i++) createOption(select, res.regions[i].id, res.regions[i].title, act);
			} else {
				//alert('Ошибка связи. Попробуйте повторить позже.');
			}
		},
		failure: function(response, options) {
			//alert('Ошибка связи. Попробуйте повторить позже.');
		},
		params: sendme
	});
}

function setSort(el,url){
	document.location=url+"sort/"+el.value+"/";
}

/* --new popup ---*/
var multi_popup = {
	oShim: null,
	oCurrDialog: null,

	show: function (params){
		$('building_complex_content').innerHTML = '';
		Ext.Ajax.request({
			url: '/ajax/load_building_complex.php',
			success: function(response, options) {
				var res = Ext.decode(response.responseText);
				$('building_complex_content').innerHTML = res.text;
				multi_popup.showPopup(params);
			},
			failure:  function(response, options) {

			},
			params: {id: params.multi_id}
		});


	}
	,


	showPopup: function(params) {
		var Dialog = document.getElementById(params.id);
		var oPopupsOuter = document.getElementById("popupsOuter");
		Dialog.style.display = 'block';
		var h = Dialog.offsetHeight;

		params.relEl = (params.relEl)? ((typeof(params.relEl)=="string")?document.getElementById(params.relEl):params.relEl) : oPopupsOuter;
		params.t = (params.t)? params.t : 0;
		params.l = (params.l)? params.l : 0;
		params.r = (params.r)? params.r : 0;
		params.pos = (params.pos)? params.pos : "l";
		if(!this.oShim){
			this.oShim = document.createElement('DIV');
			this.oShim.id = 'popupShimOuter';
			this.oShim.innerHTML = '<iframe src="javascript:false" frameBorder="0" scroll="none"></iframe>';
			document.body.appendChild(this.oShim);
			this.oShim.onclick = function(event){multi_popup.autoHide(event);};
			this.oShim.getElementsByTagName("IFRAME")[0].contentWindow.document.onclick = function(event){window.parent.popup.autoHide(event,1);};
		}


		Dialog.parentNode.onclick = function(event){multi_popup.autoHide(event);};
		Dialog.style.margin = (this.getPosY(params.relEl)+params.t)-(h+4) + "px " + params.r + "px 0 " + (this.getPosX(params.relEl) + params.l) + "px";

		if(params.w){
			Dialog.style.width = params.w + 'px';
		}

		this.oCurrDialog = Dialog;

		//this.oShim.style.display = 'block';
		Dialog.style.top = 0;
		Dialog.style.left = 0;
	}

	,

	hide: function (params){
		var Dialog = document.getElementById(params.id);
		if(this.oShim) {
			this.oShim.style.display = 'none';
		}
		//Dialog.style.top = '-1000em';
		//Dialog.style.left = '-1000em';
		Dialog.style.display = 'none';
	}
	,

	autoHide: function(event,ieFlag) {
		if(this.oCurrDialog){
			if(ieFlag){
				this.hide({id:this.oCurrDialog.id});
				this.oCurrDialog = null;
				return;
			}

			if(!event) var event = window.event;
			var targetElm = (event.target)? event.target : event.srcElement;
			if(targetElm.id == 'popupShimOuter' || targetElm.id == "popupsOuter"){
				this.hide({id:this.oCurrDialog.id});
				this.oCurrDialog = null;
			}
		}
	}
	,

	getPosY: function(o){
		var y = 0;
		while(o && o.tagName!="BODY"){
			y+= o.offsetTop + (o.clientTop || 0);
			o = o.offsetParent;
		}
		return y;
	},
	getPosX: function(o){
		var x = 0;
		while(o && o.tagName!="BODY"){
			x+= o.offsetLeft + (o.clientLeft || 0);
			o = o.offsetParent;
		}
		return x;
	}
};
function checkTree(chk){
	chk = Ext.get(chk);
	var chks = chk.parent('li');
	if(chk.dom.name) chks = chks.parent('li');
	chks = chks.query('[type="checkbox"]');
	if(chk.dom.name) {
		var sum = 0;
		Ext.each(chks, function(el,i){ if(i && el.checked) sum++; });
		if((sum!=chks.length-1 && !chk.dom.checked) || (sum==chks.length-1 && chk.dom.checked)) chks[0].checked=chk.dom.checked;
	} else Ext.each(chks, function(el,i,all){ if(i) el.checked=all[0].checked; });
	checkTreeTxt(chk.parent('[id^=select_]').prev().dom.id);
}

// tempText - returned value, that in filter file, ticket. IRRNEW-3202
var tempText;
function checkTreeTxt(cont) {
	gall = Ext.get('select_'+cont).query('input[name!=""]:checked').length;
	if (gall && !tempText) {tempText = $(cont).innerHTML;}
	$(cont).innerHTML = (gall ? 'Выбрано: '+gall : tempText);
}
function checkTreeInit(cont, clk) {
	var inps = $('sp_'+cont).value.split(',');
	var root, cnt=0, all=0, gall=0;
	Ext.each(Ext.get('select_'+cont).query("input[type='checkbox']"), function(el,i,arr) {
		if(inps.indexOf(el.value)>-1) { el.checked=true; cnt++; }
		all++;
		if(el.name=='' || i==arr.length-1) {
			if(i==arr.length-1) all++;
			if(cnt && cnt==all-1) root.checked=true;
			root=el; cnt=0; all=0;
		}
	});
	checkTreeTxt(cont);
}

function dateAdd(days){
	var dd = new Date();
	dd.setDate(dd.getDate() + days);
	return dd;
}

function displayRef(form){
	var divRef = Ext.get(form).dom;
	var no = (divRef.style.display == 'none');

	if ($('regions') && form=='add_ref_down') {
		$('regions').style.display=(no ? 'none' : '');;
	}
	divRef.style.display = (no ? 'block' : 'none');
}

// \/ auto make -> model
function plusMinusSwitch(el) {
	var table = Ext.get(el).parent().next().dom;
	var no = (table.style.display == 'none');
	el.className = (no ? 'myMinusShow' : 'myPlusShow');
	table.style.display = (no ? 'block' : 'none');
	setCookie2('m'+crc32(el.innerHTML), (no ? 1 : 0), (no ? null : -1), '/');
}
function makeClick(el,make,model) {
	if(!el) el = this;
	var formName = 'filters1';
	if(Ext.query("form[id="+formName+"]")=='') formName = 'subscriptionForm';
	if(mysetFilterValue(make+'_tmp',el.innerHTML,el,formName)==2) {
		// remove
		removeModels(el.innerHTML, formName, make+'_tmp', model);
	}
	return false;
}
function loadMake(make) {
	elShow(make+'_form');
	var make_obj = $(make);

	var model = make_obj.getAttribute('cfg').split('|')[0];

	Ext.Ajax.request({
		url: '/ajax/load_auto_models.php',
		success: function(response) {
			$(make+'_cont').innerHTML = response.responseText;

			var ids = make_obj.value;
			$(make+'_tmp').value = ids;
			if ($(model+'_tmp')) $(model+'_tmp').value = $(model).value;
			var all = ids.split(',');

			Ext.each(Ext.query('#'+make+'_form a'), function(o){
				if(all.indexOf(o.innerHTML)>-1) o.parentNode.className='selected';
				o.onclick=function() { return function(o) { makeClick(this, make, model); }; }();
				//console.log(o.onclick);
				//o.onclick=makeClick;
			});
		},
		failure: function(response) { /*alert('Системная ошибка #1');*/ },
		params: { 'cfg':(make_obj.getAttribute('dict')?make_obj.getAttribute('dict'):model) }
	});
}
function setSelectLabel(name, donthide) {
	var el = $(name);
	if (!el) return;
	var all = el.value;
	all = (all ? all.split(',').length : 0);
	$(name+'_txt').innerHTML = (all ? '<span style="color:#4F4F4F;">выбрано:</span> <span class="choosenCarTypeBg">'+all : '</a>');
	// class
	modelsLinkDisable(el, all);

	if(!donthide) {
		elHide(name+'_form');
		var m = el.getAttribute('cfg').split('|');
		$((m[2]=='' ? name : m[2])+'_tmp').value='';
		if ($((m[2]=='' ? m[0] : name)+'_tmp')) $((m[2]=='' ? m[0] : name)+'_tmp').value='';
	}
}
function modelsLinkDisable(el, all) {
	var tmp = el.name;
	el = el.getAttribute('cfg').split('|');
	if(el.length > 1 && el[0]) { // make
		if(!all) { // make==0 -> clear models
			$(el[0]).value = '';
		}
		setSelectLabel(el[0]);
	} else { // model
		el = [tmp, el[1]];
		all = 1; // for models not disable
	}
	tmp = Ext.get(el[0]+'_lnk');
	if(tmp) {
		if(all) tmp.removeClass(el[1]);
		else tmp.addClass(el[1]);
	}
}
function autoSaveSelected(name) {
	var name_obj = $(name);
	var name_cfg = name_obj.getAttribute('cfg').split('|');

	name_obj.value = $(name+'_tmp').value;
	$(name+'_tmp').value = '';

	if($(name_cfg[0]+'_tmp') && (name_cfg[2]=='')) $(name_cfg[0]).value = $(name_cfg[0]+'_tmp').value;
	setSelectLabel(name);
}
function modelClick(el,model) {
	if(!el) el = this;
	var formName = 'filters1';
	if(Ext.query("form[id="+formName+"]")=='') formName = 'subscriptionForm';

	mysetFilterValue(model+'_tmp',crc32(el.innerHTML).toString(),el,formName);
	return false;
}

function loadAutoModel(model, make) {
	 var makes = $(make).value; //.split(',');
	if(!makes) return;
	 elShow(model+'_form');
	 var mod = $(model);

	var ids = mod.value;
	$(model+'_tmp').value = ids;
	var all = ids.split(',');

	if(makes) {
		Ext.Ajax.request({
			url: '/ajax/load_auto_models.php',
			success: function(response) {
				$(model+'_cont').innerHTML = response.responseText;

				Ext.each(Ext.query('#'+model+'_form table a'), function(o){
					if(all.indexOf(crc32(o.innerHTML).toString())>-1) o.parentNode.className='selected';
					o.onclick=function() { return function(o) { modelClick(this, model); }; }();
					//o.onclick=modelClick;
				});
			},
			failure: function(response) { /*alert('Системная ошибка #2');*/ },
			params: { 'makes':makes, 'models':ids, 'cfg': (mod.getAttribute('dict')?mod.getAttribute('dict'):mod.getAttribute('cfg').split('|')[0]) }
		});
	}
}
function removeModels(maken, formn, make, model) {
	Ext.Ajax.request({
		url: '/ajax/load_auto_models.php',
		success: function(response) {
			var res = Ext.decode(response.responseText);
			for (var j = res.models.length; --j >= 0;) res.models[j] = crc32(res.models[j]);
			//console.log(res.models);
			deleteValFromField(formn,model+'_tmp',res.models);
			//setSelectLabel(model);
		},
		failure: function(response) { /*alert('Системная ошибка #3');*/ },
		params: { 'name':maken, 'cfg':$(model).getAttribute('cfg') }
	});
}
function resetAuto(el, withform) {
	var name = el.name;
	if(withform) {
		$(name+'_tmp').value = '';
	} else {
	$(name).value='';
	}
	setSelectLabel(name, withform);
	if(withform) Ext.each(Ext.query('#'+name+'_cont li a'), function(o){ o.parentNode.className=''; });
}
function elShowHide(elshow, elHide){
	if ($(elHide)) {
		$(elHide).style.display="none";
	}
	if ($(elshow)) {
		$(elshow).style.display="block";
	}
}
// /\ auto make -> model

function search_tabs(a, num) {
	var li = Ext.get(a).parent('ul').query('li');
	var tmp;
	for(i=0; i<li.length; i++) {
		Ext.get(li[i]).removeClass('activ');
		elHide('search_tab'+i);
	}
	Ext.get(li[num]).addClass('activ');
	elShow('search_tab'+num);
	setCookie2('acttab', num, null, '/');
}

AddformObject = function(form_id){
	this.form = null;
	this.error_visible = false;
	this.addEvents('fields_checked');
	this.getForm = function(){
		if (!this.form){
			this.form = $(form_id);
		}
		return this.form;
	};
	this.showError = function(t){
		var cont = Ext.get('add-error-message');
		if (!cont) return;
		this.error_visible = true;
		cont.query('h4')[0].innerHTML = t;
		cont.setStyle('display', 'block');
		window.scrollTo(0, cont.getY()-7);
	};
	this.hideError = function(){
		if (!this.isErrorVisible()) return;
		this.error_visible = false;
		var cont = Ext.get('add-error-message');
		if (!cont) return;
		Ext.get('add-error-message').setStyle('display', 'none');
	};
	this.isErrorVisible = function(){
		return this.error_visible;
	};
};

Ext.extend(AddformObject, Ext.util.Observable);


function loadVideoContent(){
	var allowSites = new Array('youtube.com','rutube.ru','video.yandex.ru');

	videoContentAreaValue = $('video_content').value.trim().replace(/[\n\r]+/gi,'');
	if(videoContentAreaValue=='') {
		$('videoContentBlock').innerHTML='Вставьте HTML&ndash; код ролика.';
		return;
	}

	//var tmp = videoContentAreaValue.match(/<object[^>]*>(.*?)<\/object>/ig);
	//if(tmp.length>1) videoContentAreaValue = tmp[0];
	tmp = videoContentAreaValue.match(/<object[^>]*>(.*?)<\/object>/ig);
	if(tmp) {
		videoContentAreaValue = tmp[0];

		siteAllow=false;
		for (i=0; i<allowSites.length && !siteAllow; i++){
			if (videoContentAreaValue.indexOf(allowSites[i])>-1) siteAllow=true;
		}
		if (!siteAllow) {
			$('videoContentBlock').innerHTML='Ролик должен быть размещен только на следующих сервисах: '+allowSites.join(', ');
			return;
		}

		var w = videoContentAreaValue.match(/width=["']*\d+["']*/g);
		var h = videoContentAreaValue.match(/height=["']*\d+["']*/g);
		w = w[0].match(/\d+/)[0];
		h = h[0].match(/\d+/)[0];

		videoContentAreaValue = videoContentAreaValue.replace(/(width=["']*\d+["']*)/ig, 'width="300"').replace(/(height=["']*\d+["']*)/ig, 'height="'+Math.round(300*h/w)+'"');
		// rutube
		videoContentAreaValue = videoContentAreaValue.replace(/name="wmode" value="(window|opaque)"/ig, 'name="wmode" value="transparent"').replace(/wmode="(window|opaque)"/ig, 'wmode="transparent"');
		// other add
		if(!videoContentAreaValue.match(/wmode/ig)) {
			videoContentAreaValue = videoContentAreaValue.replace(/\>\<param/i, '><param name="wmode" value="transparent"></param><param').replace(/\<EMBED/i, '<embed wmode="transparent"');
		}

		$('id_video').value = videoContentAreaValue;
		$('video_content').value = videoContentAreaValue;
		$('videoContentBlock').innerHTML=((window.ActiveXObject)?"<!-- -->":"")+videoContentAreaValue;
		return true;
	}

	$('videoContentBlock').innerHTML='<span style="color:red;">Вы ввели некорректный HTML&ndash; код.</span>';
}

function deleteVideoContent(){
	//$('videoContentArea').value='';
	$('videoContentBlock').innerHTML='';
	$('id_video').value = '';
	$('video_content').value = '';
	//elHide('videoContentDeleteButton');
	//$('id_video').value='';
}

function loadClickToCall(){

	if($('textarea_click_to_call').value.trim().replace(/[\n\r]+/gi,'')=='') {
		$('clickToCallBlock').innerHTML = 'Вставьте HTML&ndash; код кнопки.';
		return;
	}

	var clickToCallAreaValue = $('textarea_click_to_call').value.trim();

	if(clickToCallAreaValue.match(/www.comtube.ru/ig).length == 4) {

		$('id_click_to_call').value = clickToCallAreaValue;

		clickToCallAreaValue = clickToCallAreaValue.replace(/\<script.*?\<\/script\>/i, '');

		$('clickToCallBlock').innerHTML = clickToCallAreaValue;

		return true;
	}

	$('clickToCallBlock').innerHTML='<span style="color:red;">Вы ввели некорректный HTML&ndash; код.</span>';

	return;
}

function deleteClickToCall(){

	$('clickToCallBlock').innerHTML='';
	$('textarea_click_to_call').value = '';
	$('id_click_to_call').value = '';
}

// \/ comments
function showComment(id, obj, e) {
	var d = Ext.get('commentdialog');
	var a = Ext.get(obj);
	var form = $('comment_form').elements;

	form.id.value = id;
	Ext.Ajax.request({
		url: '/ajax/comments.php',
		success: function(response) {
			response = Ext.decode(response.responseText);
			if(response.error) {
				alert(response.error);
			} else {
				if(response.comment!=null)
				form.comment.value = response.comment;
				else
					form.comment.value ='';
				var offset = Ext.get('minWidth');
				offset = (offset ? offset.getTop() : 0);
				d.setTop(a.getTop() - offset);
				d.setLeft(a.getLeft());
				d.setStyle('display','block');
			}
		},
		failure: function() { /*alert('Системная ошибка #4');*/ },
		params: {id:id, op:'get'}
	});

	stopPropagation(e);
}
function closeComment() {
	elHide('commentdialog');
}
function removeComment() {
	closeComment();
	var id = $('comment_form').elements.id.value;

	Ext.Ajax.request({
		url: '/ajax/comments.php',
		success: function(response) {
			response = Ext.decode(response.responseText);
			Ext.get(Ext.query('a img[class*=ico-comment]', $(id))[0]).removeClass('ico-comment_activ').addClass('ico-comment');
		},
		failure: function() { /*alert('Системная ошибка #5');*/ },
		params: {op:'del', id: id}
	});
}
function saveComment() {
	var params = Ext.Ajax.serializeForm('comment_form');

	closeComment();

	Ext.Ajax.request({
		url: '/ajax/comments.php',
		success: function(response) {
			response = Ext.decode(response.responseText);
			if(response.error == '') {
				var id = $('comment_form').elements.id.value;
				Ext.get(Ext.query('a img[class*=ico-comment]', $(id))[0]).removeClass('ico-comment').addClass('ico-comment_activ');
			} else {
				alert(response.error);
			}
		},
		failure: function() { /*alert('Системная ошибка #6');*/ },
		params: params
	});
}
// /\ comments

// \/ carusel
function Carusel(cont, count) {
	var owner = $(cont);
	this.width = 90;
	this.cur = 0;
	this.min = 0;
	this.max = count - 3;
    this.flyer = Ext.get(Ext.query('ul', owner)[0]);
    this.left_btn = Ext.query('div.btn_l', owner)[0];
    this.right_btn = Ext.query('div.btn_r', owner)[0];

    this.fly = function () {
    	this.flyer.animate({
    		left: {
    			to: (-this.cur*this.width),
    			unit: 'px'
    		}
    	}, 0.35, null, 'easeIn', 'motion');
    };
    this.lb = function (v) {
    	this.left_btn.style.visibility = (v ? 'visible' : 'hidden');
    };
    this.rb = function (v) {
    	this.right_btn.style.visibility = (v ? 'visible' : 'hidden');
    };

    this.leftBtnPress = function () {
		this.rb(true);
		if (--this.cur <= this.min) {
			this.cur = this.min;
			this.lb();
		}
		this.fly();
    };
    this.rightBtnPress = function() {
		this.lb(true);
    	if (++this.cur >= this.max) {
    		this.cur = this.max;
			this.rb();
    	}
		this.fly();
    };

    this.lb();
}
// /\ carusel

function is_array(input){
    //alert (typeof(input));
    return typeof(input)=='object'&&(input instanceof Array);
}

function MultiAdvert_Stat(item,priznak,href,pr) {
    if (href!='non'){
        if(pr==0){
            document.location = href;
        }
        else if (pr==1)
            window.open(href);
    }
   if (is_array(item)){
        Ext.Ajax.request({
			url: '/ajax/ads_multi_stat.php',
			success: function() {},
			failure: function() {},
			params: { 'id[]':item, 'eventname':priznak }
		});

    }else{
        //alert(item);
    Ext.Ajax.request({
			url: '/ajax/ads_multi_stat.php',
			success: function() {},
			failure: function() {},
			params: { 'id':item, 'eventname':priznak }
		});
    }
}

function orangeMultSelect(name, params) {
	this.name = name;
	this.params = params;
	this.url = '';
}
orangeMultSelect.prototype.load = function() {
	elShow(this.name+'_form');
	var obj = $(this.name);
	this.params.ids = obj.value;
	var this_ = this;

	Ext.Ajax.request({
		url: this.url,
		success: function(response) { this_.response(response); },
		failure: function(response) { },
		params: this.params
	});
};
orangeMultSelect.prototype.response = function(response) {
	$(this.name+'_cont').innerHTML = response.responseText;
	var obj = $(this.name);
	var ids = obj.value;

	$(this.name+'_tmp').value = ids;
	var all = ids.split(',');
	var this_ = this;

	Ext.each(Ext.query('#'+this.name+'_form a'), function(o){
		if(all.indexOf(crc32(o.innerHTML).toString())>-1) o.parentNode.className='selected';
		o.onclick=function(o) { this_.click(this); };
	});
};
orangeMultSelect.prototype.click = function(el) {
	if(mysetFilterValue(this.name+'_tmp',crc32(el.innerHTML).toString(),el,'filters1')==2) {}
	return false;
};
orangeMultSelect.prototype.setSelectLabel = function(donthide) {
	var all = $(this.name).value;
	all = (all ? all.split(',').length : 0);
	$(this.name+'_txt').innerHTML = (all ? '<span style="color:#4F4F4F;">выбрано:</span> <span class="choosenCarTypeBg">'+all+'</span>' : '');

	if(!donthide) elHide(this.name+'_form');
};
orangeMultSelect.prototype.close = function() {
	this.setSelectLabel();
	return false;
};
orangeMultSelect.prototype.restore = function() {
	if($(this.name).value) this.setSelectLabel();
	return false;
};
orangeMultSelect.prototype.save = function() {
	$(this.name).value = $(this.name+'_tmp').value;
	$(this.name+'_tmp').value = '';
	this.setSelectLabel();
	return false;
};
orangeMultSelect.prototype.reset = function(withform) {
	if(withform == true) $(this.name+'_tmp').value = '';
	else $(this.name).value='';

	this.setSelectLabel(withform);
	if(withform) Ext.each(Ext.query('#'+this.name+'_cont li a'), function(o){ o.parentNode.className=''; });
	return false;
};

//start of autocatalog modifications
function getModifications(parentId, year, obj) {
	Ext.Ajax.request({
		url: '/ajax/auto/modifications.php',
		success: replaceModifications,
		//failure: failureAlert,
		headers: {},
		params: {
			parentId: parentId,
			year: year
		}
	});
	Ext.get(obj).parent('ul').select('li.act').removeClass('act');
	Ext.get(obj).parent('li').addClass('act');
}
function replaceModifications(response, options) {
	var res = Ext.decode(response.responseText);
	Ext.get('tableContainer'+ res.parentId).update(res.code);
}

//end of autocatalog modifications

//start of loading models for filter in autocatalog
function loadAutocatalogFiltersModels(makeId,el_id){
	Ext.Ajax.request({
		url: '/ajax/auto/models.php',
		success: replaceFilterModels,
		headers: {},
		params: {
			makeId: makeId,
			el_id:el_id
		}
	});
}
function replaceFilterModels(response, options){
	var res = Ext.decode(response.responseText);
	if(res.el_id!=undefined && res.el_id){
		var selectObj = $('modelsSelect_'+res.el_id);
		$('modificationSelect_'+res.el_id).innerHTML = '';
	}else
		var selectObj = $('modelsSelect');
	//clear models
	selectObj.innerHTML = '';
	//and clear bodies
	if(res.el_id!=undefined && res.el_id)
		bodies = $('bodiesSelect_'+res.el_id);
	else
		bodies = $('bodiesSelect');
	bodies.innerHTML = '';
	createOption(selectObj,'','','');
	createOption(bodies,'','','');
	setBodiesState(bodies);
	modelsCount = res['items'].length;
	for(i = 0; i < modelsCount; ++i){
		createOption(selectObj,res['items'][i]['id'],res['items'][i]['title'],'');
	}
}
//end of loading models for filter in autocatalog

//start of loading bodies for filter in autocatalog
function loadAutocatalogFiltersBodies(modelId,el_id){
	Ext.Ajax.request({
		url: '/ajax/auto/bodies.php',
		success: replaceFilterBodies,
		headers: {},
		params: {
			modelId: modelId,
			el_id:el_id
		}
	});
}
function replaceFilterBodies(response, options){
	var res = Ext.decode(response.responseText);
	if(res.el_id!=undefined && res.el_id){
		var selectObj = $('bodiesSelect_'+res.el_id);
		$('modificationSelect_'+res.el_id).innerHTML = '';
	}else
		var selectObj = $('bodiesSelect');
	selectObj.innerHTML = '';
	createOption(selectObj,'','','');
	//var t=setTimeout("setBodiesState(selectObj)",2000);
	setBodiesState(selectObj);
	modelsCount = res['items'].length;
	for(i = 0; i < modelsCount; ++i){
		createOption(selectObj,res['items'][i]['id'],res['items'][i]['title'],'');
	}
}
//end of loading bodies for filter in autocatalog

//start of loading modifications for filter in autocatalog
function loadAutocatalogFiltersModific(bodyId,el_id){
	Ext.Ajax.request({
		url: '/ajax/auto/modific_select.php',
		success: replaceFilterModific,
		headers: {},
		params: {
			bodyId: bodyId,
			el_id:el_id
		}
	});
}
function replaceFilterModific(response, options){
	var res = Ext.decode(response.responseText);
	var selectObj = $('modificationSelect_'+res.el_id);
	if (res.car_img)
		$('car_img_'+res.el_id).src = res.car_img;
	selectObj.innerHTML = '';
	createOption(selectObj,'','','');
	modelsCount = res['items'].length;
	for(i = 0; i < modelsCount; ++i){
		createOption(selectObj,res['items'][i]['id'],res['items'][i]['title'],'');
	}
}
//end of loading modifications for filter in autocatalog

function sendCompanyDetailsForm(elForm) {

	try {
		$('add-error-message').style.display='none';
	} catch (e) {}

    flagSend=true;
    setFocus = false;
    if (necessaryFields && necessaryFields.length>0){
        for (i=0; i<necessaryFields.length; i++) {
            if ($(necessaryFields[i])) {
                el=$(necessaryFields[i]);
                if (necessaryFields[i] == 'email' && !isEmail(el.value)){
                    markFieldInvalid(el.parentNode);
                    if (!setFocus) el.focus();
                    flagSend=false;
                }
                if (el.value=='') {
                    if (el.tagName == "SELECT") markFieldInvalid(el);
                    else markFieldInvalid(el.parentNode);
                    if (!setFocus) el.focus();
                    flagSend=false;
                }
            }
        }
    }
    /*
    if ($('cmp_site')) {
    	if($('cmp_site').value!='' && !$('cmp_site').value.match(/^http:\/\//)){
    		$('site_error').style.display='';
    		flagSend=false;
   		}else $('site_error').style.display='none';
   	}
    */
    try {
        var domain = $('cmp_wishsubdomain');
        if (domain.value != "" && !domain.value.match(/^([a-z0-9])+$/i)) {
            domain.value = "";
            markFieldInvalid(domain.parentNode);
            domain.focus();
            flagSend=false;
        }
    } catch(e) { }

   	if ($('captcha')) {
    	if($('captcha').value==''){
    		$('captcha_error').style.display='';
    		flagSend=false;
   		}else $('captcha_error').style.display='none';
   	}

    if (flagSend){
        return true;
    }

	try {
		$('add-error-message').style.display='block';
	} catch (e) {}

    return false;
}

function checkCompanyName(elem, display) {
    if (elem.value == '') return false;
    var params = new Array();
    params['op'] = 'check';
    params['company_name'] = elem.value;
    btn = $(display);
    Ext.Ajax.request({
            url: '/ajax/companyCheck.php',
            success: function(response, options) {
                var res = Ext.decode(response.responseText);
                if (res && res.success) {
                    if (res.is_exist) {
                        btn.style.display='block';
                        $('send_button').disabled = true;
                    }
                    else {
                        btn.style.display='none';
                        $('send_button').disabled = false;
                    }
                } else {
                    alert('Ошибка связи. Попробуйте повторить позже.');
                }
            },
            failure:  function(response, options) {
                alert('Ошибка связи. Попробуйте повторить позже.');
            },
            params: params
        });
    return true;
}

function removeAddressBlock(blockNum, addr_id) {
    if (addr_id == 0) {
        Ext.get('addressBlock'+blockNum).remove();
        necessaryFields.pop('region_id_'+blockNum);
        necessaryFields.pop('city_'+blockNum);
        return true;
    }
    Ext.Ajax.request({
        url: '/ajax/removeCompanyAddress.php',
        success: function(response, options) {
            var res = Ext.decode(response.responseText);
            if (res && res.success) {
                Ext.get('addressBlock'+blockNum).remove();
                necessaryFields.pop('region_id_'+blockNum);
                necessaryFields.pop('city_'+blockNum);
                necessaryFields.pop('street_'+blockNum);
                necessaryFields.pop('building_'+blockNum);
            } else {
                alert('Ошибка связи. Попробуйте повторить позже.');
            }
        },
        failure: function(response, options) {
                alert('Ошибка связи. Попробуйте повторить позже.');
        },
        params: {id: addr_id, op: 'remove'}
    });
}

//this function uses only in car filters
function setBodiesState(obj){
	inputs = Ext.query('#bodiesTypes li label input');
	inputsLength = inputs.length;
	for (i = 0; i < inputsLength; ++i){
		if(obj.value == ''){
			inputs[i].removeAttribute('disabled');
		}else{
			inputs[i].setAttribute('disabled', 'disabled');
		}
	}
}
function replaceAnchor(_this){
	$('select_region').style.display = 'none';
	Ext.Ajax.request({
		url: '/ajax/regions.php',
		success: function(response, options) {
			var res = Ext.decode(response.responseText);
			if (res && res.regions && res.regions.length>0) {
				var oRegions = $('oRegions');
				var el = document.createElement('OPTION');
				oRegions.innerHTML = '';
				el.value = '0';
				el.selected = true;
				el.appendChild(document.createTextNode('Выберите регион'));
				oRegions.appendChild(el);
				var aRegions = res.regions;
				for (var i = 0, n = aRegions.length; i < n; i ++) {
					el = document.createElement('OPTION');
					el.value = aRegions[i].uri;
					el.appendChild(document.createTextNode(aRegions[i].title));
					oRegions.appendChild(el);
				}
				oRegions.style.display = '';
				oRegions.focus();
			} else {
				alert('Ошибка связи. Попробуйте повторить позже.');
			}
		},
		failure: failureToGetRegion,
		params: {region: 'russia/',add_russia:1}
	});
	return false;
}
function failureToGetRegion() {
	$('waitMessageRegions').style.display = 'none';
	alert('Ошибка связи. Попробуйте повторить позже.');
	$('oRegions').style.display= 'inline';
}

function getRegion(el) {
	//setCookie2("region_url", el.value);
	setCookie2("region_url", el.value,'','/');
	$('oRegions').style.display = 'none';
	$('select_region').style.display = '';
	window.location.reload();
}
function hideSelectRegion (el){
	$('oRegions').style.display = 'none';
	$('select_region').style.display = '';

}

function getBlogCode(adv_id){
	var nocache = Math.random();
	Ext.Ajax.request({
		method: 'GET',
		url: '/advert/'+adv_id+'/',
		success: function(response) {
			$('blog_code_int').innerHTML = response.responseText;
		},
		failure: function() { alert('Ошибка связи. Попробуйте повторить позже.'); },
		headers: {},
		params: { nocache: nocache, mode: 'get' }
	});
}

function selectOnFocus(el) {
	el.setAttribute('last_value', el.selectedIndex);
	for (var i=0; option = el.options[i]; i++) {
		option.style.color = (option.disabled ? "graytext" : "menutext");
	}
}
function selectOnChange(el) {
	if(el.options[el.selectedIndex].disabled) {
		var i = el.getAttribute('last_value');
		if(i != undefined ) el.selectedIndex = i;
	} else {
		el.setAttribute('last_value', el.selectedIndex);
	}
}


//start of loading models for irr filter in autocatalog
function loadIrrFiltersModels(makeId){
	Ext.Ajax.request({
		url: '/ajax/auto/irrmodels.php',
		success: replaceIrrFilterModels,
		headers: {},
		params: {
			makeId: makeId
		}
	});
}
function replaceIrrFilterModels(response, options){
	var res = Ext.decode(response.responseText);
	var selectObj = document.getElementById('irrModelsSelect');
	//clear models
	selectObj.innerHTML = '';
	createOption(selectObj,'','','');
	modelsCount = res['items'].length;
	for(i = 0; i < modelsCount; ++i){
		createOption(selectObj,res['items'][i]['title'],res['items'][i]['title'],'');
	}
}
//end of loading models for irr filter in autocatalog

function replaceIrrFormAction(obj, action){
	//get filters form
	document.getElementById('filters1').action = action;
	Ext.get(obj).parent('tr').select('td.active').removeClass('active');
	Ext.get(obj).parent('td').addClass('active');
	if('любые' == obj.innerHTML || 'б/у' == obj.innerHTML){
		Ext.get('mileageBlock').setStyle('display', '');
	}else{
		Ext.get('mileageBlock').setStyle('display', 'none');
	}
}

function setIrrOfferType(obj){
	if('все' == obj.innerHTML){
		document.getElementById('offertype').value = '';
	}else{
		document.getElementById('offertype').value = obj.innerHTML;
	}
	Ext.get(obj).parent('tr').select('td.active').removeClass('active');
	Ext.get(obj).parent('td').addClass('active');
}


function sendInformapShowEvent(type){
	Ext.Ajax.request({
		url: '/ajax/informap/events.php',
		params: {type: type}
	});
	return false;
}

function writeInformapPhotos(photos, title) {
	var code = '', i;

	if (photos.length > 0) {
	    code += '<div id="building_icarusel" class="photo-other ph-img">';

	    if (photos.length > 3) {
	    	code += '<div class="fotoGalery">'
	    		+ '<div class="btn_l" style="visibility: hidden;">'
	    		+ '<a onclick="building_carusel.leftBtnPress();" href="javascript:;">'
	    		+ '<div></div>'
	    		+ '</a></div>'

	    		+ '<div class="center">';
	    }

	    code += '<ul class="cfix fotorow">';

	    for (i = 0; i < photos.length; i = i + 1) {
	    	code += '<li><img alt="" src="' + photos[i].preview
	    		+ '" onclick="sendInformapShowEvent(\'building_photo\');'
	    		+ 'popImage(\'' + photos[i].image + '\',\'' + title + '\');" style="cursor: pointer;"/></li>';
	    }

	    code += '</ul>';

	    if (photos.length > 3) {
	    	code += '</div><div class="btn_r">'
	    		+ '<a onclick="building_carusel.rightBtnPress();" href="javascript:;"><div></div></a>'
	    		+ '</div></div>';
	    }

	    code += '<br clear="all" style="height: 1px; display: block;" />'
	    	+ '<div class="show-zoom"><span class="ico-set"></span> '
	    	+ 'Кликните на картинку для увеличения</div></div></div>';
	}

	if (code !== '' && typeof(code) !== 'undefined') {
		$('informap-photo-block-count').innerHTML = '(' + photos.length + ')';
		$('informap-photo-block').style.display = 'block';
		$('photos_code').innerHTML = code;
	}

	if (photos.length > 3) {
		building_carusel = new Carusel('building_icarusel', photos.length);
	}
}

function loadInformapData(ad_id, only_tab){
	Ext.Ajax.request({
		url: '/ajax/informap/load_data.php',
		success: function(response, options) {
			var res = Ext.decode(response.responseText);
			if (res.success) {
				if($('hidden_photo_left') && (res.data.plans != "" || res.data.photos.length > 0)) {
					$('informap-photo-block').style.display = 'block';
					$('informap').style.paddingLeft = '';
				}
				if(!only_tab) {
				$('plan_code').innerHTML = res.data.plans;
				writeInformapPhotos(res.data.photos, res.data.title);
				}	
				if($('menu_building_info')) {
					$('menu_building_info').innerHTML = res.data.building_tab;
				}
			} else {
				return null;
			}
		},
		failure:  function(){},
		params: {ad_id: ad_id}
	});
}

function showCompanyDetails(id, event) {
	hideAllCompanies();
	$('company_details_' + id).style.display = "block";
	stopPropagation(event);
	return false;
}

function hideCompanyDetails(id, event) {
	$('company_details_' + id).style.display = "none";
	stopPropagation(event);
	return false;
}

function hideAllCompanies() {
	all_details = Ext.query('div[name="company_details"]');
	for(i=0; i<all_details.length; i++) {
		all_details[i].style.display = "none";
	}
}
function showHint(id){
	hintTimeOut=true;
	var savedCurrentHint=currentHint;
	if (currentHint) {
		hideHint();
	}
	if (id!=savedCurrentHint){
		if (document.onclick==undefined) {
			document.onclick = hideHintTimeOut;
		}
		$('hintBlockContent').innerHTML=$(id).innerHTML;
		position=getAbsolutePos($(id).parentNode);
		$('hintBlock').style.left=position.x+40+"px";
		$('hintBlock').style.top=position.y+10+"px";
		$('hintBlock').style.display="block";
		currentHint=id;
	}
}
function hideHint(){
	if (currentHint) {
		$('hintBlock').style.display="none";
		currentHint=false;
	}
}
function calculatePhotoWeight(i,str,count){

	var ind_quality = parseFloat($('id_quality_index').value);

	if (i==0 && str!='rem'){   //first foto
		ind_quality = ind_quality + parseFloat($('main_photo').innerHTML);
	}else if (i==0 && str=='rem'&& count==1){   //first foto
		ind_quality = ind_quality - parseFloat($('main_photo').innerHTML);
	}else if (i>0 && str!='rem' && i<=10){
		ind_quality = ind_quality + parseFloat($('add_photo').innerHTML);
	}else if (i>=0 && str=='rem' && count<=11){
		ind_quality = ind_quality - parseFloat($('add_photo').innerHTML);
	}
	var bar = $('bar');
	var width = bar.style.width.toString();
	var all_fields = parseInt($('all').innerHTML);
	var bar_one = parseFloat(100/all_fields);
	var num_str = Math.round(ind_quality * bar_one) + '%';
	bar.style.width = num_str;
	$('bar_down').style.width = num_str;
	$('bld_percent').innerHTML = num_str;
	$('id_quality_index').value = ind_quality;
}

function calculateWeight(obj){
	var inp = Ext.get(obj);
	try {
	var value_weight = $('weight_'+ inp.id).innerHTML;
	}
	catch (e) { return }
	if (!value_weight) return;

	var fill_str = $('fill_stat').innerHTML.toString();
	var ind_quality = parseFloat($('id_quality_index').value);
	var bar = $('bar');
	var width = bar.style.width.toString();
	var all_fields = parseInt($('all').innerHTML);
	var bar_one = parseFloat(100/all_fields);
	var pos = fill_str.search(inp.id);
	var add_id = inp.id + '!';

	if (obj.value!='' && parseInt(obj.value)!=0 && pos<0) {
		$('fill_stat').innerHTML = fill_str + add_id;
		ind_quality = ind_quality + parseFloat(value_weight);
	}
	else if (obj.value=='' && parseInt(obj.value)!=0 && pos>=0) {
		$('fill_stat').innerHTML = fill_str.substr(0,pos)+fill_str.substr(pos+add_id.length,fill_str.length);
		ind_quality = ind_quality - parseFloat(value_weight);
	}
	var num_str = Math.round(ind_quality * bar_one) + '%';
	bar.style.width = num_str;
	$('bar_down').style.width = num_str;
	$('bld_percent').innerHTML = num_str;
	$('id_quality_index').value = Math.round(ind_quality);
}
function Disable(form) {
    if (document.getElementById) {
        for (var i = 0; i < form.length; i++) {
            if (form.elements[i].type.toLowerCase() == "submit")
                form.elements[i].disabled = true;
            }
        }
        return true;
}
function isModifSelect(id){
	if(id!=undefined && $('modificationSelect_'+id).value!=''){
		compareAdd($('modificationSelect_'+id).value+'_m');
		if(id>5) compareDel(id+'_m');
		return true;
	}else
		if(id==undefined && $('modificationSelect_1').value!='' && $('modificationSelect_2').value!=''){
			compareAdd($('modificationSelect_1').value+'_m');
			compareAdd($('modificationSelect_2').value+'_m');
			return true;
		}
		else{
			alert('Выберите модификацию');
			return false;
		}
}

function makePay(ad_id,price,currency,product,days){
	if (!$('price_h').value || !$('product_h').value || !$('days_h').value) return null;
	var price_h = $('price_h').value;
	var product_h = $('product_h').value;
	var days_h = $('days_h').value;
	if (ad_id==undefined || ad_id==''){
		if(document.pay_form.eaotype.length==undefined){
			ad_id = document.pay_form.eaotype.value;
		}
		else
			for (var i=0; i < document.pay_form.eaotype.length; i++){
			   if (document.pay_form.eaotype[i].checked) ad_id = document.pay_form.eaotype[i].value;
			}
		var packet_title =  $('title_'+ad_id).innerHTML;
	}
	Ext.Ajax.request({
		url: '/ajax/make_pay.php',
		success: function(response, options) {
			var res = Ext.decode(response.responseText);
			if (res.success && res.post_data && res.post_data_hash) {
				var pay_form = $('pay_form');
				var inp1 = document.createElement('input');
				var inp2 = document.createElement('input');
				inp1.name = 'data';
				inp1.type = 'hidden';
				inp2.name = 'dataHash';
				inp2.type = 'hidden';
				inp1.value = res.post_data;
				inp2.value = res.post_data_hash;
				pay_form.appendChild(inp1);
				pay_form.appendChild(inp2);
				//alert('Все ОК');
				document.pay_form.submit();
			} else {
				alert(res.message);
				return null;
			}
		},
		failure:  function(){},
		params: {ad_id: ad_id,
				amount:price,
				currency:currency,
				product:product,
				days:days,
				price_h:price_h,
				product_h:product_h,
				days_h:days_h,
				packet_title:packet_title
		}
	});
}

function clearSelect(id) {

	var select = document.getElementById(id);
	var options = select.getElementsByTagName("option");
	var i;

	for (i=0; i<options.length; i++) {
		select.removeChild(options[i]);
	}
}

function clearAutofillFields(el) {

	try {
	var fieldsAttr = el.getAttribute('autofillfields');
	var autofillfields = fieldsAttr.split(";");

	for(var i=0; i<autofillfields.length; i++) {
		try {
			document.getElementById(autofillfields[i]).value = '';
		}
		catch(e) {}
	}
}
	catch(e) {}
}

function loadCatalogField(id, idCategory){

	$(id).disabled = 'disabled';

	clearAutofillFields(document.getElementById(id));

	var params = new Array();
	params['id_category'] = idCategory ? idCategory : document.getElementById('id_category').value;
	params['label'] = id;

	try {
		var parentsAttr = document.getElementById(id).getAttribute('parents');
		var parents = parentsAttr.split(";");

		for(var i=0; i<parents.length; i++) {
			params[parents[i]] = document.getElementById(parents[i]).value;
		}
	}
	catch (e) {}

	Ext.Ajax.request({
		url: '/ajax/load_catalog.php',
		success: function(response, options) {
			var res = Ext.decode(response.responseText);

			select = $(id);
			select.innerHTML = '';

			if (res && res.items) {

				el = document.createElement('OPTION');
				el.value = '';
				el.innerHTML = '';
				el.selected='selected';
				select.appendChild(el);

				for (var i = 0; i < res.items.length; i++) {

					el = document.createElement('OPTION');
					el.value = res.items[i].title;
					el.innerHTML = res.items[i].title;
					el.setAttribute('innerid', res.items[i].id);
					/*
						el.selected='selected';
					*/
					select.appendChild(el);
				}
			} else {
				//alert('Ошибка связи. Попробуйте повторить позже.');
			}

			$(id).disabled = '';
		},
		failure: function(response, options) {
			//alert('Ошибка связи. Попробуйте повторить позже.');

			$(id).disabled = '';
		},
		//params: {name: source.value,withany: (withany?1:0)}
		params: params
	});
}

function autofillFields(el, category) {

	clearAutofillFields(el);

	var innerId = null;

	for(var i=0; i < el.options.length; i++) {
		if(el.options[i].selected) {
			innerId = el.options[i].getAttribute('innerid');
		}
	}

	var params = new Array();
	params['innerid'] = innerId;
	params['category'] = category ? category : el.getAttribute('category');

	Ext.Ajax.request({
		url: '/ajax/load_autofill.php',
		success: function(response, options) {
			var res = Ext.decode(response.responseText);
			var items = res.items;

			for(var i=0; i<items.length; i++) {
				try {
					$('id_' + items[i].key).value = items[i].value;
				}
				catch(e) {}
			}

			try {
			document.getElementById('autofill-block').style.display = 'block';
			}
			catch(e) {
				// даже если нет кастомфилдов поля должны работать
			}
		},
		failure: function(response, options) {
			//alert('Ошибка связи. Попробуйте повторить позже.');
		},
		//params: {name: source.value,withany: (withany?1:0)}
		params: params
	});
}

function showCategoryIcon(el) {
	//el.parentNode.parentNode.style.background = "transparent url('" + el.options[el.selectedIndex].attributes['icon'].nodeVAlue + "') no-repeat scroll top right;";

	var img = Ext.get(el).next('img.category-icon', true);
	if(el.options[el.selectedIndex].attributes['icon'] != '') {
		img.src = el.options[el.selectedIndex].attributes['icon'].nodeValue;
		img.style.display = 'inline';
	} else {
		img.style.display = 'none';
	}

}

function failureCompanyGeocode(counter) {
	$('addr_latitude' + counter).value = '';
	$('addr_longitude' + counter).value = '';
	$('geo_success_message' + counter).style.display = 'none';
	$('geo_fail_message' + counter).style.display = 'block';
}

function companyGeocode(addr, counter) {
	var geocoder = new GClientGeocoder();
//	alert(addr);
	geocoder.getLocations(addr, function(obj) {
		if(obj.Status.code==G_GEO_SUCCESS) {
			var accurancy = obj.Placemark[0].AddressDetails.Accuracy;
			if(accurancy < 4) {
				failureCompanyGeocode(counter);
				return false;
			}
			var coordinates = obj.Placemark[0].Point.coordinates;
			$('addr_latitude' + counter).value = coordinates[1];
			$('addr_longitude' + counter).value = coordinates[0];
			$('geo_fail_message' + counter).style.display = 'none';
			$('geo_success_message' + counter).style.display = 'block';
		} else {
			failureCompanyGeocode(counter);
			return false;
		}
	});
}

function checkCompanyAddress(counter) {
	if(counter == undefined) counter = '';
	var street = $('street' + counter).value.trim();
	var house = $('building'+counter).value.trim();
	if(street == '' || house == '') return false;

	var region_str =  $('addr_string' + counter).value.trim();
	if(region_str == '') {
		failureCompanyGeocode(counter);
		return false;
	}

	var address_str = region_str + ', ' + street + ' ' + house;
	companyGeocode(address_str, counter);
	return true;
}


function show_comment(id){
	$(id).style.display = 'block';
}
function hide_comment(id){
	$(id).style.display = 'none';
}

function calcZoom(accuracy) {
	var zoom = 13;
	if(accuracy==5 || accuracy==6) zoom += 4; // 1
	if(accuracy==7 || accuracy==8) zoom += 5;
	if(accuracy==9) zoom += 6;
	return zoom;
}
function savesalert(url){
	Ext.Ajax.request({
		form: 'form_alert',
		callback: function (options, success, response) {
					var res = Ext.decode(response.responseText);
					if (res.success==true && res.url_goto){
						goTo(res.url_goto);
					}
					else if (res.success==true){
						//goTo('/myadverts/alerts/edit/'+res.id+'/');
						goTo('/myadverts/alerts/');
					}
					else alert('Ошибка при сохранении подписки');
				},
		params: {url:url}
	});
}
function checkUsergotoRegister(url,el){
	Ext.Ajax.request({
		form: 'form_alert',
		callback: function (options, success, response) {
			var res = Ext.decode(response.responseText);
			if(res.success){
				if (!url.match('search')) url = url+'search/';
				goTo(res.goTo+'?email='+el.email.value+'&return='+url.replace('http://' + document.domain,''));
			}
			else {
				document.getElementById('wrong_email_error_message').style.display = 'block';
			}
		}
	});
}



//Мультивыбор элементов
var multiSelectClass = function(name,value,data) {
	this.init(name,value,data);
};
multiSelectClass.prototype = {
	separator	: ',',
	prefix		: 'ms_',
	name		: '',
	value		: '',
	valueArr	: new Array(),
	data		: {},
	selected	: '',
	data_ops	: '',
	objSlt		: false,
	objSelect	: false,
	objSelected : false,
	objValue	: false,


	//Индекс эжлемента в массиве
	indexOf : function(o, arr){
		var from, len;
        len = arr.length;
        from = 0;
        for (; from < len; ++from){
            if(arr[from] === o){
                return from;
            }
        }
        return -1;
    },

	//HTML для отдельного выбранного элемента
	htmlSelectedElement : function(key,value,isLast){
		return '<a href="#" class="'+this.prefix+'element" id="'+this.prefix+'selected_'+this.name+'_'+key+'">'+value+'</a>'+((isLast)?'':', ');
	},

	//HTML выбранных элементов
	htmlSelectedElements :  function(){
		var html='';
		this.valueArr.sort();
		if (this.valueArr.length>0) {
			for (i=0; i<this.valueArr.length; i++){
				if (this.data[this.valueArr[i]]) {
					html += this.htmlSelectedElement(this.valueArr[i],this.data[this.valueArr[i]],i==this.valueArr.length-1);
				}
			}
		}
		return html;
	},

	htmlOptions : function(){
		var i,html;
		html='<select>';
		if (this.data) {
			for (i in this.data) {
				if (this.indexOf(i,this.valueArr)==-1) {
					html += '<option value="'+i+'">'+this.data[i]+'</option>';
				}
			}
		}
		html+='</select>';
		return html;
	},

	//Отображение HTML-кода сгенерированного элемента
	printElements :  function(){
		document.write(
			'<div class="'+this.prefix+'selected" id="'+this.prefix+'selected_'+this.name+'">'+this.selected+'</div>\
			<div class="'+this.prefix+'select" id="'+this.prefix+'slt_'+this.name+'">\
				<span id="'+this.prefix+'select_'+this.name+'">'+this.data_ops+'</span>\
				<a href="#" id="'+this.prefix+'button_'+this.name+'">Добавить</a>\
			</div>\
			<input type="hidden" name="'+this.name+'" value="'+this.value+'" id="'+this.prefix+this.name+'" />'
		);
	},

	//Обновление выбранных
	rePrintSelected : function(){
		this.valueArr.sort();
		this.objValue.value = this.value;
		this.objSelected.innerHTML = this.htmlSelectedElements();
		this.objSelect.innerHTML = this.htmlOptions();
		this.createElementsEvents();
	},

	//Подготовка вспомогательных данных
	prepareData :  function(){
		var i;
		if (this.value) {
			this.valueArr=this.value.split(this.separator);
		}
		this.data_ops = this.htmlOptions();
		this.selected = this.htmlSelectedElements();
	},

	//Ссылки на DOM + расстановка Events
	createObjectLinksAndEvents :  function(){
		var obj = this;
		this.objSelect = document.getElementById(this.prefix+'select_'+this.name);
		this.objSlt = document.getElementById(this.prefix+'slt_'+this.name);
		this.objSelected = document.getElementById(this.prefix+'selected_'+this.name);
		this.objValue = document.getElementById(this.prefix+this.name);
		document.getElementById(this.prefix+'button_'+this.name).onclick = function(){obj.addClickEvent(); return false};
		this.createElementsEvents();
		//Запрет на сохраненные в браузере данные
		this.value=this.valueArr.join(this.separator);
		this.objValue.value=this.value;
	},

	//Расстановка Events для выбранных
	createElementsEvents :  function(){
		var obj,childs,i;
		obj = this;
		childs = this.objSelected.getElementsByTagName('A');
		for (var i=0; i<childs.length; i++) {
			eval('childs[i].onclick = function(){obj.remClickEvent("'+childs[i].id+'"); return false}');
		}
		if (this.value=='') {
			this.objSelected.style.display='none';
		} else {
			this.objSelected.style.display='block';
		}
		if (this.objSelect.innerHTML.length<25) {
			this.objSlt.style.display='none';
		} else {
			this.objSlt.style.display='block';
		}
	},

	//Добавление элемента
	addElement : function(key){
		if (this.data[key] && this.indexOf(key,this.valueArr)==-1) {
			this.valueArr.push(key);
			this.value=this.valueArr.join(this.separator);
		}
		this.rePrintSelected();
	},

	//Удаление элемента
	remElement : function(key){
		var index;
		index = this.indexOf(key,this.valueArr);
		if (index>-1) {
			this.valueArr.splice(index,1);
			this.value=this.valueArr.join(this.separator);
		}
		this.rePrintSelected();
	},

	//Нажатие на кнопку Добавить
	addClickEvent : function(){
		var key;
		key = this.objSelect.getElementsByTagName('select')[0].value;
		this.addElement(key);
	},

	//Нажатие на выбранные элементы
	remClickEvent : function(id){
		this.remElement(id.replace(this.prefix+'selected_'+this.name+'_',''));
	},

	//Конструктор
	init :  function(name,value,data){
		this.valueArr = new Array();
		if (name) {
			this.name = name;
		}
		if (value) {
			this.value = value;
		}
		if (data) {
			this.data = data;
		}
		this.prepareData();
		this.printElements();
		this.createObjectLinksAndEvents();

	}
}

function setPaginatorItemsOnPage(select, basehref) {
	window.location = basehref + 'page_len' + select.value + '/';

}

function makePayNesprosta() {
	var list = Ext.query('#order_list input[type="checkbox"]');
	var checkedFound = false;
	var checkedList = new Array();
	var cnt;
	for (var i = 0; i < list.length; ++i) {
		if (list[i].name && list[i].checked) {
			checkedFound = true;

			cnt = list[i].id;
			checkedList.push(new Array(list[i].value, $(cnt+'_address').innerHTML, $(cnt+'_type').value, cnt/*, $(cnt+'_email').value)*/));
		}
	}
	if (!checkedFound) {
		alert('Ничего не выбрано.');
		return false;
	}
	var params = new Array();
	params['list'] = Ext.encode(checkedList);

	Ext.Ajax.request({
		url: '/ajax/make_pay_nesprosta.php',
		success: function(response, options) {
			var res = Ext.decode(response.responseText);
			if(res.msg!='') alert(res.msg);
			setCookie2('preorderedReports', res.other, 0, '/');
			goTo(res.redirect_url);
		},
		failure: function(response, options) {
			//alert('Ошибка связи. Попробуйте повторить позже.');
		},
		params: params
	});


	return 0;

}


//uses when adding order for nesprosta report
function addPreorder(reportDataObj){
	var cookieName = 'preorderedReports';
	var preorderedReports = getCookie2(cookieName);
	if(!preorderedReports){
		preorderedReports = new Array();
	}else{
		preorderedReports = Ext.util.JSON.decode(preorderedReports);
	}
	var elementIndex = -1;
	for(var i=0; i<preorderedReports.length; ++i){
		if(preorderedReports[i].id == reportDataObj.id && preorderedReports[i].field == reportDataObj.field){
			elementIndex = i;
			break;
		}
	}
	if(-1 == elementIndex){
		preorderedReports.push(reportDataObj);
	}else{
		return false;
	}
	setCookie2(cookieName, Ext.util.JSON.encode(preorderedReports), 0, '/');
}

//uses when removing order for nesprosta report
function removePreorder(reportDataObj){
	var cookieName = 'preorderedReports';
	var preorderedReports = getCookie2(cookieName);
	if( null == preorderedReports){
		preorderedReports = new Array();
	}else{
		preorderedReports = Ext.util.JSON.decode(preorderedReports);
	}
	var elementIndex = -1;
	var newArrayData = new Array();
	for(var i=0; i<preorderedReports.length; ++i){
		if((preorderedReports[i].id == reportDataObj.id) && (preorderedReports[i].field == reportDataObj.field)){
			elementIndex = i;
			continue;
		}
		newArrayData.push(preorderedReports[i]);
	}
	setCookie2(cookieName, Ext.util.JSON.encode(newArrayData), 0, '/');
	var currentUrl = location.href.replace(/\?(.*)$/, '');
	location.href = currentUrl + '?rand=' + Math.random();

}

function showHideNesprostaFieldDescription(obj){
	var currentDescriptionBlock = Ext.get(obj).parent('div').query('span.arrowNesprosta div.nesprostaDescriptionMessage');
	var currentDescriptionObj = Ext.get(currentDescriptionBlock[0]);
	var allDescriptionsBlocks = Ext.query('span.arrowNesprosta div.nesprostaDescriptionMessage');
	if(currentDescriptionObj && 'none' == currentDescriptionObj.dom.style.display){
		for(var i =0; i < allDescriptionsBlocks.length; ++i){
			Ext.get(allDescriptionsBlocks[i]).dom.style.display = 'none';
		}
		currentDescriptionObj.dom.style.display = '';
	}else{
		for(var i =0; i < allDescriptionsBlocks.length; ++i){
			Ext.get(allDescriptionsBlocks[i]).dom.style.display = 'none';
		}
	}
}