﻿window.reEmail = /^([\w\.\-])+@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/i;

var w3cDOM = (typeof document.getElementById != "undefined" && typeof document.createElement != "undefined") ? true : false;

// Fake window.onLoad.
var initJS = function() {};

function listenEvent (target, type, listener) {
	if( target==window && type=='load' ) {
		var tmp = initJS;
		initJS = function() {tmp(); listener();};
	} else if (typeof target.addEventListener != "undefined") {
		target.addEventListener (type, listener, false);
	} else if (typeof target.attachEvent != "undefined") {
		target.attachEvent ("on" + type, listener);
	}
}

function unlistenEvent (target, type, listener) {
	if (typeof target.removeEventListener != "undefined") {
		target.removeEventListener (type, listener, false);
	} else if (typeof target.detachEvent != "undefined") {
		target.detachEvent ("on" + type, listener);
	}
}


window.reEmail = /^([\w\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/i;

function restorePassword(email, success, error) {
	new Ajax.Request('/plugins/ajax/restore_password.php', {
		parameters : 'email=' + email.value,
		onSuccess  : function(transport, json) {
			$('messageRestore').innerHTML = (json.success) ? '<span class="messageError" style="color:green">'+success+'</span>' : '<span class="messageError" style="color:red">'+error+'</span>';
		}
	});
}

function strpos(haystack, needle, offset) {
    var i = (haystack+'').indexOf(needle, (offset || 0));
    return i === -1 ? false : i;
}

function setChangeImage(main_class) {
	jQuery(main_class+' .orlyAd a img').each(function (){
		if (jQuery(this).attr('large') != '') {
			jQuery(this).mouseout(function () {
				current_crs = jQuery(this).attr('large');
				jQuery(this).attr('large', jQuery(this).attr('src'));
				jQuery(this).attr('src', current_crs);
				 jQuery(this).parent().next().attr('style','margin-top:5px');
				jQuery(this).attr('style', '');
			}).mouseover(function () {
				current_crs = jQuery(this).attr('src');	
				height = jQuery(this).css('height');
				if (!strpos(height,'px')) {
					height = jQuery(this).height(); 	
				} else {
					height = height.substr(height,  strpos(height,'px'));
				} 
				jQuery(this).attr('src', jQuery(this).attr('large'));
				jQuery(this).attr('large', current_crs);
				height_2 = jQuery(this).css('height');
				if (!strpos(height_2,'px')) {
					height_2 = jQuery(this).height(); 	
				} else {
					height_2 = height_2.substr(height_2,  strpos(height_2,'px'));
				}
				height = height_2 - height - 5;
				jQuery(this).attr('style','position:relative;  z-index:10;')
				 jQuery(this).parent().next().attr('style','margin-top:-'+height+'px');	
			});
		}
	});	
}

function doLogin(message, msg_blocked) {
	jQuery.post("/plugins/ajax/login.php",
        {
            login: jQuery( "#authEmail" ).val(),
            password: jQuery( "#authPassword" ).val()
        }, function (data) {
            //console.log(data);
            //return;
            if (data.success == 1) {
                document.location = "/userarea/list/";
            } else if (data.success == 2) {
                jQuery( "#messageLogin" ).html( '<span class="messageError" style="color:red">'+msg_blocked+'</span>' );
            } else if (data.success == 3) {
                document.location = "/ppuserarea/list/";
            } else {
                jQuery( "#messageLogin" ).html( '<span class="messageError" style="color:red">'+message+'</span>' );
            }
        }, "json"
    );
}

function getEnums(parent, element, selected, first) {

	new Ajax.Request('/plugins/ajax/enums.php', {
		parameters : 'name=' + parent,
		onSuccess : function(transport, json) {

			var el;
			var select = $(element);
			select.innerHTML = '';
			if (first) {
				el = document.createElement('OPTION');
				el.value = '';
				el.innerHTML = first;
				select.appendChild(el);
			}

			for (var i = 0, n = json.items.length; i < n; i ++) {

				el = document.createElement('OPTION');
				el.value = json.items[i].id;
				if (selected) el.selected = (selected == json.items[i].id);
				el.innerHTML = json.items[i].data;
				select.appendChild(el);
			}
		}
	});
}

function showhide(theId, divID) {
	var el = document.getElementById(divID+ '-' + theId);
	var ellink = document.getElementById(divID+ '-'  + theId + '-i');

	if (el.style.display=="none") {
		el.style.display="";
		ellink.className="minus";
	}

	else {
		el.style.display="none";
		ellink.className="";
	}

	return false;
}

function showhideEl(theId, divID) {
	var el = document.getElementById(divID);
	var ellink = document.getElementById(theId);

	if (el.style.display=="none") {
		el.style.display="";
		ellink.className="minus";
	}

	else {
		el.style.display="none";
		ellink.className="";
	}

	return false;
}


function showHideFullBlock(){
	if(document.getElementById('smallBlock').style.display=='block'){
		document.getElementById('smallBlock').style.display='none';
	}else{
		document.getElementById('smallBlock').style.display='block';
	}
	if(document.getElementById('fullBlock').style.display=='block'){
		document.getElementById('fullBlock').style.display='none';
	}else{
		document.getElementById('fullBlock').style.display='block';
	}
}

function toggle(el, display) {
	if (typeof(el) == 'string') el = $(el);
	el.style.display = (el.style.display == 'none') ? '' : 'none';
}


function filterString(event) {
	var keyCode = (event.charCode) ? event.charCode : event.keyCode;
	return ((keyCode == 0) || (keyCode == 118)  || (keyCode == 99) ||(keyCode == 46) || (keyCode == 32) || (keyCode >= 34 && keyCode <= 40) || (keyCode == 8) || (keyCode == 13) || (keyCode == 37) || (keyCode == 39) || (keyCode >= 65 && keyCode <= 90) || (keyCode >= 97 && keyCode <= 122) || (keyCode >= 1040 && keyCode <= 1103));
}

function filterInteger(event) {

	if(event.ctrlKey) return false;

	if(event.shiftKey) return false;

	var keyCode = (event.charCode) ? event.charCode : event.keyCode;

	var symbol = String.fromCharCode(keyCode);
	if((symbol == 'c') || (symbol == 'v') || (symbol == "'")) return false;

	// return ((keyCode == 0) || (keyCode == 118) || (keyCode == 99) || (keyCode
	// == 8) || (keyCode == 9) || (keyCode >= 34 && keyCode <= 40) || (keyCode >
	// 47 && keyCode < 58));
	return ((keyCode == 0) || (keyCode == 8) || (keyCode >= 37 && keyCode <= 40) || (keyCode == 9) || (keyCode > 47 && keyCode < 58));
}

function filterFloat(event) {

	if(event.ctrlKey) return false;

	if(event.shiftKey) return false;

	var keyCode = (event.charCode) ? event.charCode : event.keyCode;

	var symbol = String.fromCharCode(keyCode);
	if((symbol == 'c') || (symbol == 'v') || (symbol == "'")) return false;

	var flag = false;
	if ((keyCode == 44) || (keyCode == 188) || (keyCode == 190) || (keyCode == 191) || (keyCode == 46) || (keyCode == 118) || (keyCode == 99) ||(keyCode == 46) || (keyCode == 44) || (keyCode == 0) || (keyCode == 8) || (keyCode == 9)  || (keyCode >= 34 && keyCode <= 40) || (keyCode > 47 && keyCode < 58)){
		 flag = true;
	}

	var reFloat = /[0-9]*(\.|\,)[0-9]*/i;

	var val = event.target ? event.target.value : event.srcElement.value;

	if(reFloat.test(val) && ((keyCode == 46) || (keyCode == 44) )){
		flag=false;
	}
	return flag;
}

function disallowCtrlv(event) {
	return !event.ctrlKey;
}

function filterPhone(event) {
	var keyCode = (event.charCode) ? event.charCode : event.keyCode;
	return ((keyCode >= 34 && keyCode <= 40) || (keyCode == 118) || (keyCode == 41) || (keyCode == 43) || (keyCode == 45) || (keyCode == 46) || (keyCode == 0) || (keyCode == 8) || (keyCode == 9) || (keyCode == 39) || (keyCode > 47 && keyCode < 60) || (keyCode >64 && keyCode<91) || (keyCode >96 && keyCode<123) || (keyCode >1071 && keyCode<1104) || (keyCode >1039 && keyCode<1072) || (keyCode == 32) || (keyCode == 44) || (keyCode == 44) );
}

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

function setCookie(cookieName, cookieValue, nDays, sPath) {
	var today = new Date();
	var expire = new Date();
	if (nDays == null || nDays == 0) nDays = 1;
	if (sPath == null) sPath = '/';
	expire.setTime(today.getTime() + 3600000 * 24 * nDays);
	document.cookie = cookieName + "=" + escape(cookieValue) + ";expires=" + expire.toGMTString() + ';path=' + sPath + ';domain=' + cookieDomain;
}

function showPhoto(uri, caption) {
	$('imgPhotoPreview').src = uri;
	$('captionPhoto').innerHTML = caption;
	$('imgPhotoPreviewHref').href = uri.replace('-large.','-original.');
}

function sendIncorrectInfo(adId) {
	var reason   = $('incorrect-reason');
	var comments = $('incorrect-comments');

	new Ajax.Request('/plugins/ajax/incorrect.php', {
		parameters : 'reason=' + reason.value + '&comments=' + comments.value + '&adid=' + adId,
		onSuccess  : function(transport, json) {
			if (json && json.message) {
				alert(json.message);
			} else {
				alert('Ошибка при отправке сообщения');
			}
			reason.value = '';
			comments.value = '';
			$('warningBlock').style.display = 'none';
		}
	});
}

function sendMessageToAuthor(adID) {
	var oName = $('feedbackName');
	var oEmail = $('feedbackEmail');
	var oMessage = $('feedbackMessage');
	var oPrice = $('feedbackPrice');
	var oCaptcha = $('feedbackCaptcha');
	var oCopy = $('feedbackCopy');
	var adID = $('adID');

	if (oName.value.replace(/\s/, '').length == 0) {
		alert('Укажите Ваше имя!');
		return false;
	}

	if (!reEmail.test(oEmail.value)) {
		alert('Укажите Ваш e-mail!');
		return false;
	}

	if (oMessage.value.replace(/\s/, '').length == 0) {
		alert('Укажите Ваше сообщение!');
		return false;
	}

	if (oCaptcha.value.replace(/\s/, '').length == 0) {
		alert('Укажите код антиспама!');
		return false;
	}

	new Ajax.Request('/plugins/ajax/send_feedback.php', {
		parameters : 'name='    + oName.value    + '&' +
		'ad='      + adID.value     + '&' +
		'email='   + oEmail.value   + '&' +
		'message=' + oMessage.value + '&' +
		'price='   + oPrice.value   + '&' +
		'captcha=' + oCaptcha.value + '&' +
		'copy='    + oCopy.checked,
		onSuccess : function(transport, json) {
			if (json.success) {
				alert('Ваше сообщение отослано автору объявления');
                // document.location = document.location +
				// '?rand='+Math.random();
				location.reload();
			} else if (!json.captcha) {
				alert('Укажите корректный код антиспама');
			} else {
				alert('Неизвестная ошибка');

			}
		}
	});
}


function sendToFriend(message, subject, email, success, errorCapcha, errorSenderEmail, errorRecipientEmail, errorMail) {
	var oSenderName     = $('sendSenderName');
	var oRecipientName  = $('sendRecipientName');
	var oSenderEmail    = $('sendSenderEmail');
	var oRecipientEmail = $('sendRecipientEmail');
	var oComments       = $('sendComments');
	var oAdID           = $('sendAdID');
	var oAdTitle        = $('sendAdTitle');
	var oAdText         = $('sendAdText');
	var oMessage        = $('sendMessage');
	var oSenderVercode  = $('sendervercode');

	if (!reEmail.test(oSenderEmail.value)) {
		alert( errorSenderEmail);
		/*
		 * oMessage.innerHTML = errorSenderEmail; oMessage.style.display = '';
		 */
		return false;
	}

	if (!reEmail.test(oRecipientEmail.value)) {
		alert(errorRecipientEmail);
		/*
		 * oMessage.innerHTML = errorRecipientEmail; oMessage.style.display =
		 * '';
		 */
		return false;
	}

	new Ajax.Request('/plugins/ajax/send_to_friend.php', {
		parameters : 'subject=' + subject + '&email=' + email + '&message=' + encodeURIComponent(message) + '&' +
		'sender_email=' + oSenderEmail.value + '&' +
		'sender_name=' + oSenderName.value + '&' +
		'recipient_email=' + oRecipientEmail.value + '&' +
		'recipient_name=' + oRecipientName.value + '&' +
		'comments=' + oComments.value + '&' +
		'ad_id=' + oAdID.value + '&' +
		'ad_title=' + oAdTitle.value + '&' +
		'ad_text=' + ((oAdText.innerHTML) ? oAdText.innerHTML : '' + '&' +'vercode=' +oSenderVercode.value),
		onSuccess  : function(transport, json) {
			if (json.success) {
				alert(success);
                document.location = document.location + '?rand='+Math.random();
				/*
				 * oMessage.innerHTML = success; oMessage.style.display = '';
				 */
			} else {
				if(!json.reason){
					alert(errorMail);
				}else{
					if(json.reason=='kapcha'){
						alert(errorCapcha);
					}
				}
				/*
				 * oMessage.innerHTML = errorMail; oMessage.style.display = '';
				 */
			}
		},
		onFailed : function() {
			alert(errorMail);
			/*
			 * oMessage.innerHTML = errorMail; oMessage.style.display = '';
			 */
		}
	});

	return true;
}

function signUp() {

	var params = '';
	var oEmail			= $('authEmail');
	var oPassword		= $('authPassword');
	var oPasswordRepeat	= $('authPasswordRepeat');
	var oAgree    		= $('contactAgree');
	var oName    		= $('contactFirstName');

	var reSymbols = /[^\w]/i;

	lockSendButton();

	if (!reEmail.test(oEmail.value)) {
		oEmail.focus();
		unLockSendButton();
		alert('Укажите корректный email');
		return false;
	}

	oPassword.value = oPassword.value.replace(/\s/, '');

	if (oPassword.value.length < 6) {
		unLockSendButton();
		alert('Пароль должен содержать не менее 6 символов');
		return false;
	}

	if (reSymbols.test(oPassword.value)) {
		unLockSendButton();
		alert('Пароль может содержать только буквы латинского алфавита, цифры и символ "_"');
		return false;
	}

	if (oPassword.value != oPasswordRepeat.value) {
		unLockSendButton();
		alert('Подтвердите пароль');
		return false;
	}

	if (oName.value.length < 1) {
		unLockSendButton();
		alert('Введите имя');
		return false;
	}

	if (!oAgree.checked) {
		unLockSendButton();
		alert('Для регистрации вы должны согласится с нашими условиями');
		return false;
	}

	if(!checkContactInfo('contactPhone', 'contactMobile', 'contactSite'))
	{
		unLockSendButton();
		return false;
	}

	new Ajax.Request('/plugins/ajax/check_user.php', {
		parameters : 'login=' + oEmail.value + '&' + 'captcha='    + $('contactCaptcha').value,
		onSuccess  : function(transport, json) {
			if (json.success!=0) {
				unLockSendButton();
				if (json.success == 3){
					$('contactCaptcha').focus();
					$('contactCaptcha').value='';
					alert("Неверный код антиспама");
					regetCaptcha();
				}else{
					alert('Пользователь с таким e-mail уже существует');
				}
			} else {
				new Ajax.Request('/plugins/ajax/sign_up.php', {
					parameters : 'password='   + oPassword.value              + '&' +
					'login='      + oEmail.value                 + '&' +
					'first_name=' + $('contactFirstName').value  + '&' +
					// 'last_name=' + $('contactLastName').value + '&' +
					'phone='      + $('contactPhone').value      + '&' +
					'mobile='     + $('contactMobile').value     + '&' +
					'icq='        + $('contactICQ').value        + '&' +
					'dob='        + $('contactYear').value + '-' + $('contactMonth').value + '-' + $('contactDay').value + '&' +
					'city='       + $('contactCity').value       + '&' +
					'street='     + $('contactStreet').value     + '&' +
					// 'building=' + $('contactBuilding').value + '&' +
					// 'zip=' + $('contactZIP').value + '&' +
					// 'fax=' + $('contactFax').value + '&' +
					'site='       + $('contactSite').value		 + '&' +
					'captcha='    + $('contactCaptcha').value,

					onSuccess : function(transport, json) {
						if (json && json.success){
							unLockSendButton();
							if (json.success == 2){
								$('contactCaptcha').focus();
								$('contactCaptcha').value='';
								alert("Неверный код антиспама");
								regetCaptcha();
							}else{
								/*
								 * if (document.referer) { window.location.href =
								 * document.referer; } else {
								 */
									window.location.href='/userarea/?rnd='+Math.random();
								/* } */
								// window.location.reload();
							}
						} else {
							alert('Произошла ошибка при регистрации');
						}

					},
					onFailure : function() {
						unLockSendButton();
						alert('Неизвестная ошибка');
					}
				});
			}
		}
	});

	return true;
}

function checkContactInfo(phoneId, mobileId, siteId)
{
	if(!isPhoneValid(phoneId, 'Укажите корректный контактный телефон')) return false;

	if(!isPhoneValid(mobileId, 'Укажите корректный дополнительный телефон')) return false;

	if(!isUrlValid(siteId, 'Укажите корректный сайт')) return false;

	return true;
}

function isPhoneValid(phoneId, errorMsg)
{
	var phoneRegExp = /^[+]?[0-9\-\(\) a-zа-я\.\,\;\:]{3,40}$/i;

	var userinfoPhone = jQuery('#'+phoneId).val();

	if(userinfoPhone.length > 0)
	{
		if(!phoneRegExp.test(userinfoPhone))
		{
			alert(errorMsg);
			jQuery('#'+phoneId).focus();
			return false;
		}
	}

	return true;
}

function isUrlValid(siteId, errorMsg)
{
	var userinfoSite = jQuery('#'+siteId).val();

	if(userinfoSite.length > 0)
	{
		var regExp = /^(https?:\/\/)?(([0-9a-z_!~*'().&=+$%-]+:)?[0-9a-z_!~*'().&=+$%-]+@)?(([0-9]{1,3}\.){3}[0-9]{1,3}|([0-9a-z_!~*'()-]+\.)*([0-9a-z][0-9a-z-]{0,61})+[0-9a-z]\.[a-z]{2,6})(:[0-9]{1,4})?((\/?)|(\/[0-9a-z_!~*'().;?:@&=+$,%#-]+)+\/?)$/i;

		if(!regExp.test(userinfoSite))
		{
			alert(errorMsg);
			jQuery('#'+siteId).focus();
			return false;
		}
	}

	return true;
}

function sendContact() {
	var params = '';
	var oSubject = $('contact_subject');
	var oName = $('contact_name');
	var oEmail = $('contact_email');
	var oPhone = $('contact_phone');
	var oMessage = $('contact_message');

	var reSymbols = /[^\w]/i;

	lockSendButton();

	if( oSubject.value == 0 || oSubject.value == "" ) {
		alert( "Выберите тему письма" );
		return false;
	}


	if (oName.value.length < 1) {
		unLockSendButton();
		alert('Введите имя');
		return false;
	}

	if (!reEmail.test(oEmail.value)) {
		oEmail.focus();
		unLockSendButton();
		alert('Укажите корректный email');
		return false;
	}

	if (oMessage.value.length < 5) {
		unLockSendButton();
		alert('Введите сообщение');
		return false;
	}
	var addText = oMessage.value;
    if( addText.length > 32 ) {
      	var arrayText = addText.split( /\s+/ );
       	for( var i=0; i<arrayText.length; i++ ) {
       		if( arrayText[ i ].length >= 32 ) {
       			alert('Ваш отзыв содержит слишком мало пробельных символов');
           		unLockSendButton();
           		return false;
       		}
       	}
    }


	new Ajax.Request('/plugins/ajax/send_contact.php', {
		parameters : 'subject=' + oSubject.value +'&' +
		'name='   + oName.value              + '&' +
		'email='      + oEmail.value                 + '&' +
		'phone='      + oPhone.value      + '&' +
		'message='     + oMessage.value,

		onSuccess : function(transport, json) {
			unLockSendButton();
			if (json && json.success){
				alert("Ваше сообщение успешно отправлено");
				window.location.reload();
			} else {
				alert('Произошла ошибка при отправке');
			}
		},
		onFailure : function() {
			unLockSendButton();
			alert('Неизвестная ошибка');
		}
	});

	return false;
}

function regetCaptcha(){
	$('captchaImg').writeAttribute('src','/vendors/kcaptcha/?time=' + Math.random());
}

function lockSendButton(){
	// $('contactSend').up(3).insert(new Element('img', {id:
	// 'ajax-loader',style: 'margin:3px 0 0 10px',src:
	// '/webroot/delivery/pic/ajax-loader.gif'}));
	$('contactSend').value="Отправка";
	$('contactSend').writeAttribute('disabled', 'disabled');
}

function unLockSendButton(){
	// if($('ajax-loader')) $('ajax-loader').remove();
	$('contactSend').value="Отправить";
	$('contactSend').removeAttribute('disabled');
}

function getMarks(category){

	new Ajax.Request('/plugins/ajax/marks.php', {
		parameters  : 'category=' + category,
		onSuccess   : function(transport, json) {
			options = '<option value="0">все марки</option>';
			// alert("fadfs");
			if (200 == transport.status) {
				for(i=0; i<json.marks.length; i++){
					options+='<option value="'+json.marks[i].id+'">'+json.marks[i].data+'</option>';
				}
				$('search-mark').innerHTML = options;
                $('search-mark').disabled = false;
			}

		}
		});


}

/* Скрипты относящиеся к ppuserarea */
function toggleStatBlock() {
	jQuery( '.statistica table' ).toggle();
	jQuery( '.statistica small.floatRight' ).toggleClass( 'plus' );
	jQuery( '.statistica span' ).toggle( function() {
		jQuery( this ).css( {
			marginBottom:'0px',
			padding: '0px',
			background: 'none'
		} );
	}, function() {
		jQuery( this ).css( {
			marginBottom:'10px',
			padding: '0 0 3px',
			background: 'transparent url(../pic/brd.gif) repeat-x scroll 0 100%;'
		} );
	} );
	return false;
}
/* end_of Скрипты относящиеся к ppuserarea */

/* листалка объявлений на главной */

var adsCount = 3;
var startAdsPosition = adsCount; // при загрузке произойдет откат до 0
var maxAdsPosition = null; // стартовое значение - для того чтобы первые клики
							// прошли, потом более точное подтянется с сервера


function nextAds()
{
	if(startAdsPosition == 0) return;

	startAdsPosition -= adsCount;
	if(startAdsPosition < 0) startAdsPosition = 0;
	loadAdsMain();
}

function prevAds()
{
	if(startAdsPosition == maxAdsPosition) return;

	startAdsPosition += adsCount;
	if(maxAdsPosition != null)
	{
		if(startAdsPosition > maxAdsPosition) startAdsPosition = maxAdsPosition;
	}
	loadAdsMain();
}

function loadAdsMain()
{
	var url = '/plugins/ajax/get_ads_main.php?start='+startAdsPosition+'&count='+adsCount;

	jQuery.get(url,
        function(data){
    	maxAdsPosition = data.max;

        var show_block = false;

    	for (var i = 1; i < 4; ++i) {
    		if (data['ad' + i]) {
    			show_block = true;
    			adPutToBlock(data['ad' + i], 4 - i);
    		}
    	}

		var nextClass = 'prev_galery';

		if(startAdsPosition == 0) nextClass += ' prev_galery_no_activ';

		jQuery('#button-next').attr('class', nextClass);

		var prevClass = 'next_galery';

		if(startAdsPosition == maxAdsPosition) prevClass += ' next_galery_no_activ';

		jQuery('#button-prev').attr('class', prevClass);

		if (show_block) {
				jQuery('#ads-list').css('display', 'block');
        	}
        });
}

function adPutToBlock(item, number)
{
	jQuery('#ad-img-link-' + number).attr('href', item.href);
	jQuery('#ad-img-' + number).attr('src', item.img);
	jQuery('#ad-link-' + number).attr('href', item.href);
	jQuery('#ad-link-' + number).html(item.text);

	if(parseInt(item.price)) {
		jQuery('#ad-price-' + number).html(item.price);
	}
	else {
		jQuery('#ad-price-' + number).html('');
	}

	jQuery('#ad-region-' + number).html(item.region);

	item.premium ? $('ad-premium-' + number).show() : $('ad-premium-' + number).hide();

	if(item.isset_image) {
		$('ad-img-link-' + number).show();
	}
	else {
		$('ad-img-link-' + number).hide();
	}
}

/* end_of листалка объявлений на главной */

function clickPath(inpName, catId, url)
{
	jQuery('#hidden-search').attr('action', url);

	jQuery('#make-id').val(catId);
	jQuery('#make-id').attr('name', inpName);

	jQuery('#hidden-search').submit();
	return false;
}

function makePremium(adId, isPPArea) {

	var divId = 'ad-prem-' + adId;

	$(divId).toggle();
}

function prolongPremium(adId, isPPArea) {

	var divId = 'ad-prem-' + adId;

	$(divId).toggle();
}
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 categoryFilterFormValidate() {

	var category_id = jQuery('#category_id').val();
    var special_cat = category_id.indexOf('special',0);

	//Redirects for `special` category

	//if (category_id == 'special') {
    if(special_cat!=-1){
		var redirect_url = jQuery('#filter-specialtype-id option:selected').attr('url');

		if (redirect_url != '') {

			jQuery('#categoryFilterForm').attr('action', redirect_url);
		}
	}

	var make = '';
	make = jQuery('#filter-make-id').val() ? jQuery('#filter-make-id option:selected').text() : make;
	make = jQuery('#filter-truck_make-id').val() ? jQuery('#filter-truck_make-id option:selected').text() : make;
	make = jQuery('#filter-trailer_make-id').val() ? jQuery('#filter-trailer_make-id option:selected').text() : make;
	make = jQuery('#filter-bus_make-id').val() ? jQuery('#filter-bus_make-id option:selected').text() : make;
	make = jQuery('#filter-special_make-id').val() ? jQuery('#filter-special_make-id option:selected').text() : make;

	var model = '';
	model = jQuery('#filter-model-id').val() ? jQuery('#filter-model-id option:selected').text() : model;
	model = jQuery('#filter-truck_model-id').val() ? jQuery('#filter-truck_model-id option:selected').text() : model;
	model = jQuery('#filter-trailer_model-id').val() ? jQuery('#filter-trailer_model-id option:selected').text() : model;
	model = jQuery('#filter-bus_model-id').val() ? jQuery('#filter-bus_model-id option:selected').text() : model;
	model = jQuery('#filter-special_model-id').val() ? jQuery('#filter-special_model-id option:selected').text() : model;

	var newAction = jQuery('#categoryFilterForm').attr('baseaction');
    if(special_cat!=-1){
	//if(category_id == 'special') {

		if(jQuery('#filter-specialtype-id option:selected').attr('path')) {

			var newAction = jQuery('#filter-specialtype-id option:selected').attr('path');

			jQuery('#filter-specialtype-id').attr('disabled', 'disabled');
		}
	}

	make = jQuery.trim(make);
	model = jQuery.trim(model);

	if(make) {
		newAction += make + '/';
	}

	if(model) {
		newAction += model + '/';
	}

	var optionUrl = jQuery('#filter-region_id').val();

	var newUrl = optionUrl + newAction;

	jQuery('#categoryFilterForm').attr('action', newUrl);

	jQuery('#filter-region_id').attr('disabled', 'disabled');

	return true;
}

function categoryFilterFormAdditionalFieldsVisibilityChecker() {

	// Selector for non-empty attributes
// $.expr[':'].withAttr = function(obj, index, meta, stack){
// return ($(obj).attr(meta[3]) != '');
// };

	var container = jQuery('#dop_parametrs');
	var filled = false;
	if (jQuery('input:checked', container).size() > 0) {
		// Checkboxes
		filled = true;
	} else if (jQuery('option:selected[value]', container).size() > 0) {
		// Selects
		filled = true;
	} else if (jQuery('input:text[value]', container).size() > 0) {
		filled = true;
	}

	if (filled) {
		jQuery('#dop_parametrs').show();
	}

	return false;
}


function adsListChooseCurrency(currency_id) {
	if (ads_currency_current != currency_id) {
		jQuery('#currency_switcher_' + ads_currency_current).removeClass('currency_active');
		jQuery('span.currency_' + ads_currency_current).hide();
		ads_currency_current = currency_id;
		jQuery('#currency_switcher_' + ads_currency_current).addClass('currency_active').blur();
		jQuery.cookie('adslist_currency', currency_id, {
	        domain: cookieDomain,
	        path: '/',
	        expires: 0
	    });
		jQuery('span.currency_' + ads_currency_current).show();
	}
	return false;
}

function sitemapToggleNode(li) {

	if(li.className == 'plus') {
		li.className = 'minus';
	}
	else {
		li.className = 'plus';
	}
}


var newAction = false;
function searchFormSubmit() {

	var isCorrectInput = ($('search-keywords').value=='ключевое слово, модель и т.д.');
	isCorrectInput == isCorrectInput || ($('search-keywords').value=='');
	isCorrectInput = isCorrectInput || ($('search-keywords').value.match(/[a-zA-Zа-яА-Я0-9]{2,}.+/) == null ? false : true);

	if(!isCorrectInput) return false;

	/*

	if(
		(
			($('search-keywords').value=='ключевое слово, модель и т.д.') ||
			($('search-keywords').value=='') ||
			(!$('search-keywords').value.match(/[a-zA-Zа-яА-Я0-9]{2,}.+/))
		) &&
		( $('search-category').value==1 ) &&
		( jQuery('#search-region option:selected').attr('domain') == '' )
		)
	{
		return false;
	}
	*/

	if(document.getElementById('search-keywords').value=='ключевое слово, модель и т.д.') {
		document.getElementById('search-keywords').value = '';
	}

	if (! newAction) {
		newAction = jQuery('#search-form').attr('action');
	}
	var optionUrl = jQuery('#search-region').val();
	var newUrl = optionUrl + newAction;

	jQuery('#search-region').attr('disabled', 'disabled');
	jQuery('#search-form').attr('action', newUrl);

	return true;
}

function searchPopupSubmit() {

	if(jQuery('#search-category').val() == 0) {
		/* alert('Поле Категория обязательно для заполнения'); */
		return false;
	}
	else {

		if(jQuery('#search-region').val() != 0) {

			var optionUrl = jQuery('#search-region').val();

			if (! newAction) {
				newAction = jQuery('#filterFormFromMain').attr('action');
			}

			var newUrl = optionUrl + newAction;
			jQuery('#search-region').attr('disabled', 'disabled');

			jQuery('#filterFormFromMain').attr('action', newUrl);
		}

		return true;
	}
}

function initFavoritesPage()
{
	jQuery('.add-comment-link').click(function () {
		startFavoriteCommentEdit(this.id.split('-')[3]);
		return false;
	});

	jQuery('.edit-comment-link').click(function () {
		var parent;
		parent = jQuery(this).parents('.b-ChoseComent');
		startFavoriteCommentEdit(parent.get(0).id.split('-')[2]);
		return false;
	});

	jQuery('.edit-comment-link-save').click(function () {
		var parent;

		parent = jQuery(this).parents('.b-ChoseComent');
		saveFavoriteComment(parent.get(0).id.split('-')[2]);
		return false;
	});

	jQuery('.edit-comment-link-cancel').click(function () {
		var parent;

		parent = jQuery(this).parents('.b-ChoseComent');
		cancelFavoriteCommentEdit(parent.get(0).id.split('-')[2]);
		return false;
	});
}

function startFavoriteCommentEdit(id)
{
	var parent, comment, text;

	jQuery('#add-comment-link-' + id).hide();

	parent = jQuery('#comment-editor-' + id);
	parent.show();

	parent.addClass('b-comentRedact');
	parent.find('.edit-comment-link-save, .edit-comment-link-cancel').show();
	parent.find('.edit-comment-link').hide();

	comment = parent.children('.coment');
	text = comment.text();
	comment.html('<textarea>' + text + '</textarea>');
	comment.children('textarea').focus();
	comment.children('textarea').get(0).originalText = text;
}

function cancelFavoriteCommentEdit(id)
{
	var text;

	text = jQuery('#comment-editor-' + id + ' textarea').get(0).originalText;

	setFavoriteComment(id, text);
}

function saveFavoriteComment(id)
{
	var text, parent;

	parent = jQuery('#comment-editor-' + id);
	text = parent.find("textarea").val();

	parent.find('.edit-comment-link-save, .edit-comment-link-cancel').hide();

	postFavoriteToServer(id, text, function () {
		setFavoriteComment(id, text);
	});
}

function setFavoriteComment(id, text)
{
	var parent = jQuery('#comment-editor-' + id);
	if (text === '') {
		parent.hide();
		jQuery('#add-comment-link-' + id).show();
	} else {
		parent.removeClass('b-comentRedact');
		parent.find('.edit-comment-link-save, .edit-comment-link-cancel').hide();
		parent.find('.edit-comment-link').show();
	}

	parent.children('.coment').text(text);
}

function initFavoritesPopup()
{
	var popup = jQuery('#coment_popup');
	popup.find('#comment-popup-close').click(function () {
		popup.hide();
		return false;
	});
	popup.find('#comment-popup-submit').click(function () {
		var text = jQuery('#comment-popup-text').val(),
			adId = jQuery('#comment-popup-adid').val();

		postFavoriteToServer(adId, text, function () {
			popup.hide();
		});
	});
}

function add_to_favourites(adId) {
	var popup, w, centerDiv;

	popup = jQuery('#coment_popup');
	if (popup.length === 0) {
		postFavoriteToServer(adId, '');
	} else {
		popup.show();
		centerDiv = jQuery('#comment-popup-position');

		w = jQuery(window);
        centerDiv.css('top', w.scrollTop() + w.height() / 2 - centerDiv.height() / 2);
        jQuery('#comment-popup-adid').val(adId);
	}
    return false;
}

function postFavoriteToServer(adId, comment, callback) {
	comment = comment || '';

    jQuery.post('/plugins/ajax/add_to_favourites.php',
        {
    		'ad_id': adId,
    		'comment': comment
        },
        function(data) {
            // Menu
            var fav = jQuery('#menuitem_favourites');
            if (data.count > 0) {
                jQuery('span', fav).html('[' + data.count + ']');
                fav.show();
            } else {
                fav.hide();
            }

           // Link & message
           jQuery('#fav_' + adId + '_lnk').hide();
           jQuery('#fav_' + adId + '_msg').show();

           if (typeof callback === 'function') {
        	   callback();
           }
        }
    );
}

function reloadCatalogModels(category) {

	var selectedMake = jQuery('#catalog_make').val();
	if(typeof(category) == 'undefined'){
		category = '';
	}

	if(selectedMake) {
	    jQuery.get('/plugins/ajax/catalog_get_models.php',
	        {'make': selectedMake, 'category' : category},
	        function(data) {
        		$('catalog_model_container').innerHTML = data;
	        },
	        'html'
	    );
	}else{
		jQuery('#catalog_model').find('option').remove();
	}
}

function catalogPopupSubmit() {

	var makeUrl = jQuery('#catalog_make option:selected').attr('url');
	var modelUrl = jQuery('#catalog_model option:selected').attr('url');

	if(!makeUrl) return false;

	var url = makeUrl;

	if(modelUrl) {
		url += '/' + modelUrl;
	}

	url = '/' + url + '/';

	document.location.href = url;

	return false;
}

function zoom_zoom(obj) {

	if (obj.style.position != 'absolute') {

		obj.style.oldPosition 	= obj.style.position;
		obj.style.oldWidth 		= obj.style.width;
		obj.style.oldMarginTop 	= obj.style.marginTop;

		obj.style.position = 'absolute';
		obj.style.width = '200px';
		obj.style.marginTop = '-25px';
	}
	else {
		obj.style.position 	= obj.style.oldPosition;
		obj.style.width 	= obj.style.oldWidth;
		obj.style.marginTop = obj.style.oldMarginTop;
	}
}

function userareaMessageShow(adId, type) {

	var oldStyle = $('ad-'+type+'-' + adId).style.display;

	try {
		$('ad-prem-' + adId).style.display = 'none';
	} catch(e) {};

	try {
		$('ad-pushup-' + adId).style.display = 'none';
	} catch(e) {};

	try {
		$('ad-selected-' + adId).style.display = 'none';
	} catch(e) {};

	if(oldStyle == 'block') {
		$('ad-'+type+'-' + adId).style.display = 'none';
	}
	else {
		$('ad-'+type+'-' + adId).style.display = 'block';
	}

	return false;
}




/* Фотогалерея в отзывах */

var adsCount = 3;
var startAdsPosition = adsCount; // при загрузке произойдет откат до 0
var maxAdsPosition = null; // стартовое значение - для того чтобы первые клики
							// прошли, потом более точное подтянется с сервера


function nextAds()
{
	if(startAdsPosition == 0) return;

	startAdsPosition -= adsCount;
	if(startAdsPosition < 0) startAdsPosition = 0;
	loadAdsMain();
}

function prevAds()
{
	if(startAdsPosition == maxAdsPosition) return;

	startAdsPosition += adsCount;
	if(maxAdsPosition != null)
	{
		if(startAdsPosition > maxAdsPosition) startAdsPosition = maxAdsPosition;
	}
	loadAdsMain();
}

function loadAdsMain()
{
	var url = '/plugins/ajax/get_ads_main.php?start='+startAdsPosition+'&count='+adsCount;

	jQuery.get(url,
        function(data){
    	maxAdsPosition = data.max;

        var show_block = false;

    	for (var i = 1; i < 4; ++i) {
    		if (data['ad' + i]) {
    			show_block = true;
    			adPutToBlock(data['ad' + i], 4 - i);
    		}
    	}

		var nextClass = 'prev_galery';

		if(startAdsPosition == 0) nextClass += ' prev_galery_no_activ';

		jQuery('#button-next').attr('class', nextClass);

		var prevClass = 'next_galery';

		if(startAdsPosition == maxAdsPosition) prevClass += ' next_galery_no_activ';

		jQuery('#button-prev').attr('class', prevClass);

		if (show_block) {
				jQuery('#ads-list').css('display', 'block');
        	}
        });
}

function adPutToBlock(item, number)
{
	jQuery('#ad-img-link-' + number).attr('href', item.href);
	jQuery('#ad-img-' + number).attr('src', item.img);
	jQuery('#ad-link-' + number).attr('href', item.href);
	jQuery('#ad-link-' + number).html(item.text);

	if(parseInt(item.price)) {
		jQuery('#ad-price-' + number).html(item.price);
	}
	else {
		jQuery('#ad-price-' + number).html('');
	}

	jQuery('#ad-region-' + number).html(item.region);

	item.premium ? $('ad-premium-' + number).show() : $('ad-premium-' + number).hide();

	if(item.isset_image) {
		$('ad-img-link-' + number).show();
	}
	else {
		$('ad-img-link-' + number).hide();
	}
}

/* end_of Фотогалерея в отзывах */

function Subscribe() {

    var organization = $('organization');
    var index = $('index');
    var town = $('town');
    var street = $('street');
    var house = $('house');
    var structure = $('structure');
    var office = $('office');
    var contact = $('contact');
    var phone = $('phone');
    var email = $('email');
    var number_of_copy = $('number_of_copy');
    var number_of_copy = $('number_of_copy');
    var region = $('region');
    var district = $('district');

    $('SubscriptionSend').style.display="none";
	$('SubscriptionSend').style.visibility="hidden";
    var error = '';

    if(organization.value==''){
        if (error=='') error += 'название организации';
            else error +=', название организации';
    }

    if(index.value==''){
        if (error=='') error += 'индекс';
            else error +=', индекс';
    }
    if(region.value==''){
        if (error=='') error += 'область';
            else error +=', область';
    }

    if(district.value==''){
        if (error=='') error += 'район';
            else error +=', район';
    }

    if(town.value==''){
        if (error=='') error += 'город';
            else error +=', город';
    }

    if(street.value==''){
        if (error=='') error += 'улица';
            else error +=', улица';
    }

    if(house.value==''){
        if (error=='') error += 'дом';
            else error +=', дом';
    }
    if(structure.value==''){
        if (error=='') error += 'строение';
            else error +=', строение';
    }
    if(office.value==''){
        if (error=='') error += 'офис';
            else error +=', офис';
    }
    if(contact.value==''){
        if (error=='') error += 'контактное лицо';
            else error +=', контактное лицо';
    }
    if(phone.value==''){
        if (error=='') error += 'контактный телефон';
            else error +=', контактный телефон';
    }
    if(email.value==''){
        if (error=='') error += 'e-mail';
            else error +=', e-mail';
    }
    if(number_of_copy.value==''){
        if (error=='') error += 'количество экземпляров';
            else error +=', количество экземпляров';
    }
    if(error!=''){
        $('SubscriptionSend').style.visibility="visible";
        $('SubscriptionSend').style.display="block";
        alert('Заполните, пожалуйста, следующие поля:'+error+'!');
        return false;
    }

    new Ajax.Request('/plugins/ajax/subscribe_for_magazine.php', {
					parameters :
                    'organization='+ organization.value + '&' +
					'activity='+ $('activity').value + '&' +
					'identify_numder_of_taxpayer=' + $('identify_numder_of_taxpayer').value  + '&' +
					'index='      + index.value + '&' +
                    'region='     + region.value + '&' +
                    'district='   + district.value + '&' +
					'town='       + town.value    + '&' +
					'street='     + street.value        + '&' +
					'house='      + house.value + '&' +
					'structure='  + structure.value + '&' +
					'office='     + office.value    + '&' +
					'time_from='  + $('time_from').value + '&' +
                    'time_to='    + $('time_to').value + '&' +
					'contact='    + contact.value + '&' +
                    'position='   + $('position').value + '&' +
					'phone='      + phone.value + '&' +
                    'fax='        + $('fax').value + '&' +
					'email='      + email.value + '&' +
                    'period_from='  + $('period_from').value + '&' +
                    'period_to='    + $('period_to').value + '&' +
					'number_of_copy='    + number_of_copy.value + '&' +
                    'add_data='    + $('add_data').value,

					onSuccess : function(transport, json) {
						if (json && json.success){
							$('SubscriptionSend').style.visibility="visible";
                            $('SubscriptionSend').style.display="block";
                            alert("Ваша заявка на подписку отправлена");
                            window.location.href='/about/autocom/';
							} else {
							alert('Произошла ошибка при отправке данных');
                            $('SubscriptionSend').style.visibility="visible";
                            $('SubscriptionSend').style.display="block";
						}

					},
					onFailure : function() {
                        $('SubscriptionSend').style.visibility="visible";
                        $('SubscriptionSend').style.display="block";
						alert('Неизвестная ошибка');
					}
				});

	return true;
}


function getUrlVars()
{
    var vars = [], hash;
    var hashes = document.location.href.slice(document.location.href.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++)
    {
        hash = hashes[i].split('=');
        vars[decodeURIComponent(hash[0])] = decodeURIComponent(hash[1]);
    }
    return vars;
}

function updateSubscriptionDataCookie()
{
    var data, subscriberType;
    if (jQuery('#subscribe-type').length == 0) {
        return null;
    }
    subscriberType = jQuery('#subscribe-type').val();
    data = {
        'type': subscriberType,
        'category': jQuery('#subscribe-category').val(),
        'region': currentRegionId
    };
    switch (subscriberType) {
        case 'SearchKeyword':
            var terms = document.location.href.match(/\/search\/(.+)\//);
            if (terms !== null) {
                var termsArray = terms[1].split('/');
                data.terms = termsArray[termsArray.length - 1];
            }
            break;

        case 'SearchAds':
            jQuery('[name^=filter_]').each(function () {
                if (this.value) {
                    data[this.name] = this.value;
                }
            });
            break;

        case 'Review':
            var getParameters = getUrlVars();
            if (getParameters['reviews_query'] !== undefined &&
                getParameters['reviews_query'] !== ''
            ) {
                data['query'] = getParameters['reviews_query'];
            }
            if (jQuery('#subscribe-review-type').val()) {
                data['review-type'] = jQuery('#subscribe-review-type').val();
            }
            jQuery('.reviews-subscribe-field').each(function () {
                if (this.checked) {
                    data[this.name] = 1;
                }
            });
            break;
    }

    jQuery.cookie('subscribe_list_data', jQuery.toJSON(data), {
        domain: cookieDomain,
        path: '/'
    });
    return data;
}

function initSubscriptionPopup()
{
	jQuery('#subscription-popup-link').click(function () {
		jQuery('#subscription-popup').toggle();
		return false;
	});

	jQuery('#subscription-popup-close').click(function () {
		jQuery('#subscription-popup').hide();
		return false;
	});

	jQuery('#search-results-email-text').focus(function () {
		var ec = jQuery('#search-results-email-custom').get(0);
		if (ec) {
			ec.checked = true;
		}
	});

    // Only cookie on page load matters
    var data = updateSubscriptionDataCookie();
    if (data === null) {
        data = jQuery.evalJSON(jQuery.cookie('subscribe_list_data'));
    }

	jQuery('#search-results-email-submit').click(function () {
		var customEmailInput, defaultEmail, doNotSendEmail;
		customEmailInput = jQuery('#search-results-email-custom');
		if (customEmailInput.length > 0) {
            doNotSendEmail = true;
			defaultEmail = !customEmailInput.get(0).checked;
		} else {
            doNotSendEmail = false;
			defaultEmail = 0;
		}
        data.default_email = defaultEmail;
        data.email = jQuery('#search-results-email-text').val();
        data.period = jQuery('#search-results-email-period').val();

	    jQuery.post('/plugins/ajax/search_results_subscribe.php',
	        data,
	        function(data) {
	        	if (data) {
	        		if (data.success) {
	        			if (!doNotSendEmail) {
	        				alert('Письмо с подтверждение отправлено на ваш e-mail');
	        			} else {
	        				alert('Подписка добавлена');
	        			}
	        			jQuery('#subscription-popup').hide();
	        		} else {
	        			if (data.message) {
	        				alert(data.message);
	        			} else {
	        				alert('Произошла ошибка');
	        			}
	        		}
    			} else {
    				alert('Произошла ошибка');
    			}
	        }
	    );

	    return false;
	});
}

function initSubscribesPage()
{
    jQuery('.toggle_description_popup').click(function () {
        jQuery(this).find('.popup').toggle();
    });

    jQuery('.userarea-subscriptions-delete').click(function () {
        var items = jQuery('.subscription-delete-checkbox:checked');

        if (items.length === 0) {
            alert('Не выбрано ни одной подписки.');
            return;
        }

        if (!confirm(
                'Вы действительно хотите удалить ' +
                (items.length === 1 ? 'эту подписку' : 'эти подписки') + '?')
        ) {
            return;
        }

        var ids = [];
        items.each(function () {
            ids.push(this.id.split('-')[1]);
        });

        jQuery.post('/plugins/ajax/unsubscribe.php',
            {
                'ids': ids.join(',')
            },
            function(data) {
                if (data) {
                    if (data.success) {
                        window.location.reload();
                    } else {
                        alert('Произошла ошибка');
                    }
                } else {
                    alert('Произошла ошибка');
                }
            }
        );
    });
}


/** * catalog/compare ** */

function compareSelectMake(id){
	if (jQuery('#compare_make').children().length < 2){
		jQuery('#catalog-popup-form2 select').attr('disabled', true);
		var usual_text = jQuery('#catalog-popup-form2 p').text();
		jQuery('#catalog-popup-form2 p').text('Загрузка, подождите пожалуйста');

		new Ajax.Request('/plugins/ajax/compare.php', {
			parameters :
	        'id='+ id + '&' +
	        'op=selectMake' + '&' +
	        'current=' + encodeURIComponent(window.location.href.match(/(\d+)/g).join('/')),

			onSuccess : function(transport, json) {
				if (json && json.success){
					for (var i=0; i<json.items.length;i++){
						jQuery('#compare_make').append('<option value="'+json.items[i].id+'">'+json.items[i].make+'</option>');
					}
				} else {
					alert('Ошибка загрузки данных');
				}

				jQuery('#catalog-popup-form2 select').removeAttr('disabled');
				jQuery('#catalog-popup-form2 p').text(usual_text);

			},
			onFailure : function() {
				jQuery('#catalog-popup-form2 select').removeAttr('disabled');
				jQuery('#catalog-popup-form2 p').text(usual_text);
				alert('Неизвестная ошибка');
			}
		});
	}
}

function compare_change_popup_photo(url){
	jQuery('#compare_popup_img').children().remove();
	jQuery('#compare_popup_img').append('<img src="'+url+'" />');
}

function compareSelectModels(id, make_id){
		jQuery('#catalog-popup-form2 select').attr('disabled', true);
		var usual_text = jQuery('#catalog-popup-form2 p').text();
		jQuery('#catalog-popup-form2 p').text('Загрузка, подождите пожалуйста');

		new Ajax.Request('/plugins/ajax/compare.php', {
			parameters :
				'id='+ id + '&' +
				'op=selectModel' + '&' +
		        'make='+make_id,

			onSuccess : function(transport, json) {
				if (json && json.success){
					jQuery('#compare_model').children().remove();
					jQuery('#compare_model').append('<option value=""></option>');
					for (var i=0; i<json.items.length;i++){
						jQuery('#compare_model').append('<option img="'+json.items[i].img_url+'" value="'+json.items[i].id+'">'+json.items[i].model+'</option>');
					}
				} else {
					alert('Ошибка загрузки данных');
				}

				jQuery('#catalog-popup-form2 select').removeAttr('disabled');
				jQuery('#catalog-popup-form2 p').text(usual_text);

			},
			onFailure : function() {
				jQuery('#catalog-popup-form2 select').removeAttr('disabled');
				jQuery('#catalog-popup-form2 p').text(usual_text);
				alert('Неизвестная ошибка');
			}
		});
}

function removeCompare(id, obj){
	jQuery(obj).remove();
	var saved_ids = jQuery.cookie('compare');
	if (saved_ids){
		saved_ids = saved_ids.match(/(\d+)/g);

		saved_ids = jQuery.grep(saved_ids, function(v) {
			return v != id;
		});

	}else{
		saved_ids = [];
	}

	jQuery.cookie('compare', saved_ids, {
        domain: cookieDomain,
        path: '/',
        expires: 0
    });

	if (saved_ids.length > 0){
		renderCompareBlock(true);
	}else{
		jQuery('#compare-block').hide();
	}
}

function addToCompare(id){
	// <!-- li class="actLi black"><a href="#">Man TGX</a> <a
	// href="javascript:removeFavorites(this);"><div
	// class="ico-close"></div></a></li-->
	// jQuery('#compare-block
	// li:not(.actLi):first').addClass('actLi').append('<a href="#">Man TGX</a>
	// <a href="javascript:removeFavorites(this);"><div
	// class="ico-close"></div></a>');
	var already = false;

	var saved_ids = jQuery.cookie('compare');
	if (saved_ids){
		saved_ids = saved_ids.match(/(\d+)/g);
		if (saved_ids.length >= 4) return;
		for (var i=0; i<saved_ids.length; i++){
			if (saved_ids[i] == id){
				already = true;
				break;
			}
		}
	}else{
		saved_ids = [];
	}

	if (!already){
		jQuery.cookie('compare', (saved_ids.length > 0 ? saved_ids+','+id : id), {
	        domain: cookieDomain,
	        path: '/',
	        expires: 0
	    });
		renderCompareBlock(true);
	}

}

function renderCompareBlock(rebuild){
	var saved_ids = jQuery.cookie('compare');
	if (saved_ids){
		saved_ids = saved_ids.match(/(\d+)/g);

		jQuery('#compare-block').show();
		if (saved_ids.length > 1){
			jQuery('#compare-block div[class="btn"]').show();
		}else{
			jQuery('#compare-block div[class="btn"]').hide();
		}

		new Ajax.Request('/plugins/ajax/compare.php', {
			parameters :
				'op=fetchModelName' + '&' +
		        'model_ids='+saved_ids.join(','),

			onSuccess : function(transport, json) {
				if (json && json.success){
					if (rebuild){
						jQuery('#compare-block li').removeClass('actLi').html('');
					}
					for (var i=0; i<json.items.length; i++){
						jQuery('#compare-block li:not(.actLi):first').addClass('actLi').html('<!-- link -->'+json.items[i].make+' '+json.items[i].model+' <a href="javascript:removeCompare('+json.items[i].id+', this);"><div class="ico-close"></div></a>');
					}
				} else {
					alert('Ошибка загрузки данных');
				}

			},
			onFailure : function() {
				jQuery('#catalog-popup-form2 select').removeAttr('disabled');
				jQuery('#catalog-popup-form2 p').text(usual_text);
				alert('Неизвестная ошибка');
			}
		});

	}
}

function goToCompare(){
	var saved_ids = jQuery.cookie('compare');
	if (saved_ids){
		saved_ids = saved_ids.match(/(\d+)/g);
		if (saved_ids.length > 0){
			window.location.href = '/catalog/comparison/data/' + saved_ids.join('/')+'/';
		}
	}
}

/*
 * B2BContext
 */

function initTenders()
{
	jQuery(function () {
		jQuery('#href_short').click(function () {
			jQuery('.b2bcontext_find_header, .b2bcontext_find_content').toggle();
			jQuery('input#show_short').val('none');
			jQuery('input#show_form').val('block');
		});

		var revertChanges = function () {
			var parent = jQuery(this).parents('.b-checkUl');
			parent.find('.b2btree_item_checkbox').each(function () {
				this.checked = this.savedState;
			});
			var selectedCount = parent.find('.b2btree_item_checkbox:checked').length;
			parent.siblings('input[readonly]').val('Выбрано ' + selectedCount);
		};

		// Categories popup
		jQuery('#b2bcontext_otr_popup_link').click(function () {
			jQuery('#b2bcontext_otr_popup').toggle();
			return false;
		});
		jQuery('#b2bcontext_otr_popup_close, #b2bcontext_otr_popup_cancel').click(function () {
			revertChanges.call(this);
			jQuery('#b2bcontext_otr_popup').hide();
			return false;
		});
		jQuery('#b2bcontext_otr_popup_select').click(function () {
			jQuery('#b2bcontext_otr_popup').hide();
			return false;
		});

		// Countries popup
		jQuery('#b2bcontext_country_popup_link').click(function () {
			jQuery('#b2bcontext_country_popup').toggle();
			return false;
		});
		jQuery('#b2bcontext_country_popup_close, #b2bcontext_country_popup_cancel').click(function () {
			revertChanges.call(this);
			jQuery('#b2bcontext_country_popup').hide();
			return false;
		});
		jQuery('#b2bcontext_country_popup_select').click(function () {
			jQuery('#b2bcontext_country_popup').hide();
			return false;
		});

		// Tree handling
		jQuery('.b2btree_popup_link').click(function () {
			jQuery(this).parent().find('.b2btree_item_checkbox').each(function () {
				this.savedState = this.checked;
			});
		});
		jQuery('.b2btree-tree-handler').click(function () {
			jQuery(this).siblings('ul.b2btree_subitems').toggle();
			jQuery(this).parent().toggleClass('act').toggleClass('levelNext_act');
			return false;
		});
		jQuery('.b2btree_item_checkbox').click(function (event) {
			event.stopPropagation();

			// Down
			var subItemsStatus = this.checked;
			jQuery(this).parent().siblings('ul.b2btree_subitems').find('.b2btree_item_checkbox').each(function () {
				this.checked = subItemsStatus;
			});

			// Up
			jQuery(this).parents('ul.b2btree_subitems').each(function () {
				var notCheckedCount = jQuery(this).find('.b2btree_item_checkbox:not(:checked)').length;
				jQuery(this).siblings('label').children('.b2btree_item_checkbox')[0].checked = (notCheckedCount === 0);
			});

			var selectedCount = jQuery(this).parents('.b2btree').find('.b2btree_item_checkbox:checked').length;
			jQuery(this).parents('.b-checkUl').siblings('input[readonly]').val('Выбрано ' + selectedCount);
		});
		jQuery('.b2btree_select_all').click(function() {
			var parent = jQuery(this).parents('.b-checkUl');
			parent.find('.b2btree_item_checkbox').each(function () {
				this.checked = true;
			});
			var selectedCount = parent.find('.b2btree_item_checkbox:checked').length;
			parent.siblings('input[readonly]').val('Выбрано ' + selectedCount);
			return false;
		});
		jQuery('.b2btree_select_none').click(function () {
			var parent = jQuery(this).parents('.b-checkUl');
			parent.find('.b2btree_item_checkbox').each(function () {
				this.checked = false;
			});
			parent.siblings('input[readonly]').val('Выбрано 0');

			return false;
		});
	});
}

function initResearches() {
	jQuery(function () {
		jQuery('.researches-category-table').click(function () {
			jQuery(this).find('.expand-image, .collapse-image').toggle();
			jQuery(this).next().toggle();
		});
	});
}

/*
 * Web-id
 */
function initWebId() {
    jQuery(function () {
        jQuery('.b-webId .web-id-enter').click(function() {
            jQuery('.b-webId .addPass').show();
            jQuery(this).hide();
        });

        jQuery('.b-webId .web-id-add').click(function() {
            jQuery('.b-webId .web-id-error').hide();
            jQuery.ajax({
                url: '/plugins/ajax/webid.php',
                data: {
                    ad_id: jQuery('.b-webId .web-id-ad-id').val(),
                    webid: jQuery('.b-webId .web-id-web-id').val(), 
                    password: jQuery('.b-webId .web-id-password').val()
                },
                success: function(data) {
                    if (data.success) {
                        jQuery('.b-webId .web-id-message').html('Обьявление добавлено в Ваш личный кабинет');
                        jQuery('.b-webId .web-id-notchecked').hide();
                        jQuery('.b-webId .web-id-valid').show();
                        jQuery('.b-webId .addPass').hide();
                    } else {
                        jQuery('.b-webId .web-id-error').html('<b>' + data.message + '</b>');
                        jQuery('.b-webId .web-id-error').show();
                    }
                },
                error: function () {
                    alert('Ошибка отправки данных, попробуйте позже.');
                }
            });
        });

        jQuery('#webid-submit-button').click(function () {
            var webid, phone, location = '';

            webid = jQuery('input#webid').val();

            if (webid != '') {
                location += 'webid:' + webid + '/';
            }

            phone = jQuery('input#phone').val();
            if (phone != '') {
                location += 'phone:' + phone + '/';
            }

            if (location != '') {
                document.location.href = '/cars/search/' + location;
            }
        });
    });
}


function FeedbackValidate() {
	if (jQuery('#name').attr('value') != '' && jQuery('#phone').attr('value') != '' && jQuery('#email').attr('value') != '' && jQuery('#contactCaptcha').attr('value') != '') {
		error_message = "Не правильно введены поля:\n";
		show_message = false;
		
		email_reg = /[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/;
		email = jQuery('#email').attr('value');
		
		phone = jQuery('#phone').attr('value');
		phone_reg = /^(\+?\d+)?\s*(\(\d+\))?[\s-]*([\d-]*)$/;
		
		if(!phone.match(phone_reg)){
			show_message = true;
			error_message += "- Телефон\n";
			jQuery('#phone').attr('value','');			
		}
		if (!email.match(email_reg)) {
			show_message = true;
			error_message += "- Email";
			jQuery('#email').attr('value', '');
		} 
		if (show_message == true) { 
			alert(error_message);
			return false;	
		} 
		jQuery('#feedbackForm').submit();
	} else { 
		error_message = 'Заполните следующие поля:\n';
		if (jQuery('#name').attr('value') == '') {
			error_message += '- Имя\n';	
		} 
		if (jQuery('#phone').attr('value') == '') {
			error_message += '- Телефон\n';	
		} 
		if (jQuery('#email').attr('value') == '') {
			error_message += '- E-mail\n';	
		} 
		if (jQuery('#contactCaptcha').attr('value') == '') {
			error_message += '- Защита от спама\n';	
		} 
		
alert(error_message); return false;	}	
}
