$.ajaxSetup({
	//data: {rnd: Math.random()},
	dataType: 'json',
	cache: false
});

$(function() {

	//handler call function trimTitle
	(function() {
		var advertTitle = $('.associatedGoods.two-columns  ul li .h3 a');
		advertTitle.each(function() {
			trimTitle($(this), 25);
		});
		/**
		 * this function trim the title up to two lines
		 * @param $el jQuery object title
		 * @param height height two lines
		 */
		function trimTitle($el, height) {
			if ($el.height() > height) {
				var words = $el.html().split(/\s+/);
				words.pop();
				$el.html(words.join(' ') + '...')
				trimTitle($el, height);
			}
			return;
		}
	})()

	// if banner is load, add class to container
	$('.checkIsSetBanner').find('div[id^="bw_place_"]:visible').livequery(function() {
		var el = $(this).parents('.checkIsSetBanner');
		var className = el.data('banner-class');
		if (className.length) {
			el.addClass(className);
		}
	});

	// if banner is loaded, remove class from container
	$('.checkIsUnsetBanner').find('div[id^="bw_place_"]:visible').livequery(function() {
		var el = $(this).parents('.checkIsUnsetBanner');
		var className = el.data('banner-class');
		if (className.length) {
			el.removeClass(className);
		}
	});

	// Setup only-in-cur-cat value
	$('#only-in-cur-cat-field').change(function () {
		if ($(this).prop('checked')) {
			if ($('#filter input[name=keywords]').length) {
				$('#filter input[name=keywords]').val( $('#id_keywords').val() );
			}
		} else {
			if ($('#filter input[name=keywords]').length) {
				$('#filter input[name=keywords]').val('');
			}
		}
	});
	$.ajax({
		cache: false,
		url:'/ajax/topline.php',
		success:function(data) {
			$('.top .wrapLinkRight').html(data);
			setFavCounters();
		},
		dataType:'html'
		});


	if ($('.yandexDirect').html() != '') {
		$('.yandexDirect').show();
	}

	//Search line
	var def = 'Введите ключевое слово, id объявления или номер телефона';
	var search = $('#id_keywords');
	if (search.val() == '') {
		search.val(def);
	}
	search.bind({
		focus: function() {
			if (search.val() == def) {
				search.val('');
				search.parent().parent().removeClass('wrSearchNoactive');
			}
		},
		blur: function() {
			if (search.val() == '') {
				search.parent().parent().addClass('wrSearchNoactive');
				search.val(def);
			}
		}
	});

	//Footer width
	var height = $('#footer').height();
	var padding = height + 35 + 'px;';
	$('#minWidth').attr('style', 'padding-bottom:' + padding);
	$('#footer').css({bottom: 0, 'position':'absolute'});


	if (typeof mostPopularGoodsOnMainPage != 'undefined') {
		var goodsSlider = new popularGoodsSlider(mostPopularGoodsOnMainPage);
		goodsSlider.init();
	}


	$('.block_links_lk').live('click',function() {
		$('#block_links_h:visible').hide();
		$('#block_links_lk').fadeToggle(0);
		return false;
	});

	$('#load_user_ads_counter').live('click', function() {
		$.popup.showActivity($('#block_links_lk'));
		if (!$(this).data('is_loaded')) {
			$(this).data('is_loaded', 1);
			$.ajax({
				url: '/ajax/get_user_ads_counter.php',
				dataType : 'json',
				success: function(data) {
					$("#user_ads_counter").text(data.count);
					$.popup.hideActivity();
				},
				failure: function() {
					$("#user_ads_counter").text(0);
					$.popup.hideActivity();
				}
			});
		} else {
			$.popup.hideActivity();
		}
	});


	//show breadcrumbs popup
	$('.breadcrumbsPopup').mouseenter(function() {
		hidePopups();
		off = $(this).position();
		bcp = $('#bcPopup' + $(this).attr('id'));
		$(bcp).css('top', off.top);
		$(bcp).css('left', off.left);
		$(bcp).show();
		wUl = $(bcp).find("ul").width();
		$(bcp).width(wUl);
	});

	$('.breadcrumbsPopupList').mouseleave(function() {
		if ($('.breadcrumbsPopupList').is(':visible')) {
			$('.breadcrumbsPopupList').hide();
		}
	});

	$('body').mouseup(function() {
		hidePopups();
	});

	$('.popupHideable').mouseup(function() {
		return false;
	});

	$('#clear_searches_cookie').click(function() {
		$.cookie('my_searches', null, {
			//path: $('#default_cookie_path').val(),
			path: '/',
			domain: $('#site_cookie_path').val()
		});
		$('#my_searches_list').remove();
		$('#clear_searches_cookie').parent().remove();
		return false;
	});

	$('#clearLastShowAdverts').click(function() {
		$.cookie('advert_view_history', null, {
			path: $('#default_cookie_path').val(),
			domain: $('#site_cookie_path').val()
		});
		$('#clearLastShowAdverts').parents('.lastShowGoods').remove();
		return false;
	});


	//  functions
	$('#phone-parent-i').click(function() {
		$('#phone-parent').toggle();
		return false;
	});

	$('#phone-2-i').click(function() {
		$('#phone-2').toggle();
		return false;
	});

	$('#phone-3-i').click(function() {
		$('#phone-3').toggle();
		return false;
	});

	$('#phone-2-1-i').click(function() {
		$('#phone-2-1').toggle();
		return false;
	});

	$('#phone-3-1-i').click(function() {
		$('#phone-3-1').toggle();
		return false;
	});

	$('#mobile-parent-i').click(function() {
		$('#mobile-parent').toggle();
		return false;
	});

	$('#mobile-1-i').click(function() {
		$('#mobile-1').toggle();
		return false;
	});

	$('#offline-parent-i').click(function() {
		$('#offline-parent').toggle();
		return false;
	});

	/**
	 * form validation for step_2 (int)
	 */
	$('.validate_int').numberMask({beforePoint:20,defaultValueInput:'',checkData:true});
	/**
	 * form validation for step_2 (float)
	 */
	$('.validate_float').numberMask({type:'float',beforePoint:20,defaultValueInput:''});

	$('.add_customfields_show_link').click(function() {
		var $row = $(this).parent().parent().next();
		if ($row.is(':visible')) {
			$row.hide();
			$('img', $(this)).removeClass('ico-blueStrT').addClass('ico-blueStrB');
		} else {
			$row.show();
			$('img', $(this)).removeClass('ico-blueStrB').addClass('ico-blueStrT');
		}
		return false;
	});

	//call init checkbox multiselect
	setHandlerCheckboxForMultiselect()

	if ($('.b-adListTable.b-favoriteTable tr :checkbox').length > 0) {
		$('#clipboardAddsPrintBtn').show();
	}


	// handler submit powerSellers search form
	(function() {
		var $submitBtn = $('#powerSellers_search_form_result');
		$submitBtn.click(function() {
			var query_str = $('#query_string').val();
			if(query_str.length == 0) {
				return false;
			}
			var searchString;
			if ($('#search_pselelrs').prop('checked')) {
				searchString = '/powerSellers/list/search/keywords=' + encodeURIComponent(query_str) + '/';
				window.location = searchString;
			} else if ($('#search_adverts').prop('checked')) {
				searchString = '/powerSellers/ads_list/search/keywords=' + encodeURIComponent(query_str) + '/';
				window.location = searchString;
			}
			return false;
		});
		$('#powerSellers_search_form').submit(function(){
			$submitBtn.click();
			return false;
		})
	})();
});

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

	videoContentAreaValue = $.trim($('#video_content').val()).replace(/[\n\r]+/gi, '');
	if (videoContentAreaValue == '') {
		$('#videoContentBlock').html('Вставьте HTML&ndash; код ролика.');
		$('#uploadedVideo').show();
		toggleMask(false);
		$('#popupVideoAdd').hide();
		$('#linkVideoAdd').hide();
		return;
	}

	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').html('Ролик должен быть размещен только на следующих сервисах: ' + allowSites.join(', '));
			$('#uploadedVideo').show();
			$('#linkVideoAdd').hide();
			toggleMask(false);
			$('#popupVideoAdd').hide();
			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"');
		}

		$('#f_video').val(videoContentAreaValue);
		$('#video_content').val(videoContentAreaValue);
		$('#videoContentBlock').html(((window.ActiveXObject) ? "<!-- -->" : "") + videoContentAreaValue);
		$('#uploadedVideo').show();
		$('#linkVideoAdd').hide();
		return true;
	}
	$('#linkVideoAdd').hide();
	$('#uploadedVideo').show();
	$('#videoContentBlock').html('<span style="color:red;">Вы ввели некорректный HTML&ndash; код.</span>');
}



function filterScrollResults(n_win, n_docel, n_body) {
	var n_result = n_win ? n_win : 0;
	if (n_docel && (!n_result || (n_result > n_docel)))
		n_result = n_docel;
	return n_body && (!n_result || (n_result > n_body)) ? n_body : n_result;
}

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

function getCookie(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 incFavCounter(val) {
	var favCounter = $('#clipboardCount-1');
	if (favCounter.get(0)) {
		var old_value = favCounter.html().replace(/\(|\)/g, '');
		old_value = (isNaN(parseInt(old_value)) ? 0 : parseInt(old_value));
		var count = old_value + val;
		if (count < 0) count = 0;
		favCounter.html(count ? '(' + count + ')' : '');
	}

	var favCounter = $('#clipboardCount-2');
	if (favCounter.get(0)) {
		var old_value = favCounter.html().replace(/\(|\)/g, '');
		old_value = (isNaN(parseInt(old_value)) ? 0 : parseInt(old_value));
		if (count < 0) count = 0;
		favCounter.html(count ? '(' + count + ')' : '');
	}
}

function setFavCounters() {
	var count = 0;
	var not_auth_cookie = getCookie('una');
	if (not_auth_cookie) {
		var fav_cookie = getCookie('favorites_1');
		if (fav_cookie) {
			var cookie_array = fav_cookie.split(',');
			for (i = 0; i < cookie_array.length; i++) {
				if (cookie_array[i] != '' && cookie_array[i] != null) {
					count++;
				}
			}
		}
		var fav_cookie = getCookie('favorites_2');
		if (fav_cookie) {
			var cookie_array = fav_cookie.split(',');
			for (i = 0; i < cookie_array.length; i++) {
				if (cookie_array[i] != '' && cookie_array[i] != null) {
					count++;
				}
			}
		}
		count = count ? '(' + count + ')' : '';
		var favCounter = $('#clipboardCount-1');
		if (favCounter) {
			favCounter.html(count);
		}
		var favCounter = $('#clipboardCount-2');
		if (favCounter) {
			favCounter.html(count);
		}
	} else {
		$.ajax({
			url: '/ajax/favorites.php?' + Math.random(),
			type: "POST",
			data: ({op: 'count'}),
			dataType: 'json',
			success: function(response) {
				if (! response.success) {
					alert(response.msg);
				}
				count = response.data;
				count = count ? '(' + count + ')' : '';
				var favCounter = $('#clipboardCount-1');
				if (favCounter) {
					favCounter.html(count);
				}
				var favCounter = $('#clipboardCount-2');
				if (favCounter) {
					favCounter.html(count);
				}
			}
		});
	}
}

function hidePopups() {
	$('.popupHideable').hide();
}



function resetForm(selector) {
	$(':text, :password, :file, textarea', selector).val('');
	$(':input, select option', selector)
			.removeAttr('checked')
			.removeAttr('disabled')
			.removeAttr('selected');
	$('select', selector).prop('selectedIndex', 0);
}

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 submitFilters(form, form2, form3) {

	var form = form || document.getElementById('filters');
	var basehref = form.action.replace('http://' + document.domain, '');
	var locality = jQuery('#region_label').val();
	var def = 'Введите ключевое слово, id объявления или номер телефона';
	var search = jQuery('#id_keywords');
	if ((search.val() == def || $.trim(search.val()) == '') && ($(form).attr('id') == 'filters')) {
		return false;
	}

	if($(form).attr('id')=='filters') {
		if ($('#only-in-cur-cat-field').length && $('#only-in-cur-cat-field').prop('checked')) {
			// leaf category or advert page
			if ($('#filter').length) {
				// leaf cat with own filter block
				if ($('#filter input[name=keywords]').length) {
					$('#filter input[name=keywords]').val( $('#id_keywords').val() );
				} else {
					$('#filter').append('<div class="filterItem rows" data-item-name="keywords" data-item-type="text">\n\
										<div class="lbl"><div class="floatLeft"> Ключевые слова &nbsp; </div></div>\n\
										<div class="hid-o"><ul><li><div class="chk-b " style="height: 20px;">\n\
										<input type="text" autocomplete="off" value="' + $('#id_keywords').val() + '" name="keywords">\n\
										</div></li></ul></div></div>');
				}
				$('#show-result-search').click();
				return false;
			} else {
				// advert page
				var advert_loc = $('#advert-rubric-uri').text() + 'search/keywords=' + encodeURIComponent($('#id_keywords').val()) + '/';
				document.location.href = advert_loc;
				return false;
			}
		}
	}

	basehref += locality ? locality + '/' : '';

	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]);
		}
	}

	if (form3) {
		if (form3.id) {
			searchstring += createFilter(form3);
		} else {
			for (var i = 0; i < form3.length; i++)	searchstring += createFilter(form3[i]);
		}
	}

	if (searchstring != '') {
		var new_location = basehref + '/search/' + searchstring;
	} else {
		var new_location = basehref + '/';
	}

	document.location = new_location.replace('//', '/');

	return false;
}

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

	if (el.elements) {
		//url = preURL;
		for (var 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;
}

/**
 * Example: wordEnding(5, 'документ', '', 'а', 'ов'); return "документов".
 * @param num
 * @param wordroot
 * @param end1
 * @param end2
 * @param end3
 */
function wordEnding(num, wordroot, end1, end2, end3) {
	if (num.toString().length >= 3) {
		num = num.toString().substring(num.toString().length - 2, num.toString().length);
	}
	if (Number(num) <= 20) {
		var last = Number(num);
	} else {
		var last = num.toString().substring(num.toString().length - 1, num.toString().length);
	}
	var ending = '';
	switch (Number(last)) {
		case 1:
			ending = end1;
			break;
		case 2:
		case 3:
		case 4:
			ending = end2;
			break;
		default:
			ending = end3;
			break;
	}
	return wordroot + ending;
}

/**
 * Class for popular goods slide pages on main page
 * @param params
 */
var popularGoodsSlider = function(params) {
	this.params = params;
	this.currentPage = 0;
	this.pageCount = this.params.length;
	this.itemsPerPage = 4;

	this.init = function() {
		var self = this;
		if (this.pageCount > 0) {
			$('#mostPopularGoodsNext').click(function() {
				if (self.currentPage + 1 >= self.pageCount) {
					self.currentPage = 0;
				} else {
					++ self.currentPage;
				}
				self.renderPage();
				return false;
			});
			$('#mostPopularGoodsPrev').click(function() {
				if (self.currentPage - 1 < 0) {
					self.currentPage = self.pageCount - 1;
				} else {
					-- self.currentPage;
				}
				self.renderPage();
				return false;
			});
		} else {
			$('#mostPopularGoodsNext,#mostPopularGoodsPrev').hide();
		}
	}

	this.renderPage = function() {
		var page = this.params[this.currentPage];
		this.renderUpperGood(page);
		this.renderOtherGoods(page);
	}

	this.renderUpperGood = function(page) {
		var upperSection = $('#mostPopularGoods table.adListTable');
		if (typeof page[0].photo[0] != 'undefined') {
			$('.tdImg img', upperSection).attr('src', page[0].photo[0].url_medium2);
			$('.tdImg img', upperSection).attr('alt', page[0].photo[0].title);
		} else {
			$('.tdImg img', upperSection).attr('src', '/site/pic_dis/zaglushka160x160.gif');
		}
		var allAdvertsUrl = '/searchads/search/make=' + page[0].make + '/model=' + crc32(page[0].model) + '/';
		$('.tdTxt a', upperSection).attr('href', page[0].all_href);
		$('.tdImg a', upperSection).attr('href', page[0].all_href);
		$('.tdTxt a', upperSection).html(page[0].make + ' ' + page[0].model);
		$('.tdTxt p', upperSection).html(page[0].text);
		//new advert
		if (page[0].new_adverts != null) {
			if (typeof page[0].new_adverts.count != 'undefined') {
				$('td.tdPrise div.floatLeft a', upperSection).attr('href', allAdvertsUrl + 'used-or-new=new/');
				$('td.tdPrise div.floatLeft a', upperSection).html(page[0].new_adverts.count + wordEnding(page[0].new_adverts.count, ' новы', 'й', 'х', 'х'));
			}
			if (typeof page[0].new_adverts.price_from != 'undefined' && typeof page[0].new_adverts.price_to != 'undefined') {
				$('td.tdPrise div.floatLeft div.prise', upperSection).html(page[0].new_adverts.price_from + ' - ' + page[0].new_adverts.price_to + ' р.');
			}
		} else {
			$('td.tdPrise div.floatLeft a', upperSection).attr('href', '');
			$('td.tdPrise div.floatLeft a', upperSection).html('');
			$('td.tdPrise div.floatLeft div.prise', upperSection).html('');
		}
		//used adverts
		if (page[0].used_adverts != null) {
			if (typeof page[0].used_adverts.count != 'undefined') {
				$('td.tdPrise div.floatRight a', upperSection).attr('href', allAdvertsUrl + 'used-or-new=used/');
				$('td.tdPrise div.floatRight a', upperSection).html(page[0].used_adverts.count + wordEnding(page[0].used_adverts.count, ' подержаны', 'й', 'х', 'х'));
			}
			if (typeof page[0].used_adverts.price_from != 'undefined' && typeof page[0].used_adverts.price_to != 'undefined') {
				$('td.tdPrise div.floatRight div.prise', upperSection).html(page[0].used_adverts.price_from + ' - ' + page[0].used_adverts.price_to + ' р.');
			}
		} else {
			$('td.tdPrise div.floatRight a', upperSection).attr('href', '');
			$('td.tdPrise div.floatRight a', upperSection).html('');
			$('td.tdPrise div.floatRight div.prise', upperSection).html('');
		}
	}

	this.renderOtherGoods = function(page) {
		for (var i = 1; i < this.params[this.currentPage].length; i ++) {
			var item = $('#mostPopularGoods table.adListUl td:eq(' + (i - 1) + ')');
			if (typeof page[i].photo[0] != 'undefined') {
				$('.wrImg img', item).attr('src', page[i].photo[0].url_medium1);
				$('.wrImg img', item).attr('alt', page[i].photo[0].title);
			} else {
				$('.wrImg img', item).attr('src', '/site/pic_dis/zaglushka100x100.gif');
			}

			var allAdvertsUrl = '/searchads/search/make=' + page[i].make + '/model=' + crc32(page[i].model) + '/';
			$('div.h3 a', item).attr('href', page[i].all_href);
			$('div.wrImg a', item).attr('href', page[i].all_href);
			$('div.h3 a', item).html(page[i].make + ' ' + page[i].model);
			if (page[i].all_adverts != null && typeof page[i].all_adverts.count != 'undefined') {
				$('p a', item).attr('href', allAdvertsUrl);
				$('p a', item).html(page[i].all_adverts.count + wordEnding(page[i].all_adverts.count, ' объявлени', 'е', 'я', 'й'));
			} else {
				$('p a', item).attr('href', '');
				$('p a', item).html('&nbsp;');
			}
			//new advert
			if (page[i].new_adverts != null) {
				if (typeof page[i].new_adverts.count != 'undefined') {
					$('p.gray:eq(0)', item).html(page[i].new_adverts.count + wordEnding(page[i].new_adverts.count, ' новы', 'й', 'х', 'х'));
				}
				if (typeof page[i].new_adverts.price_from != 'undefined' && typeof page[i].new_adverts.price_to != 'undefined') {
					$('p.prise:eq(0)', item).html(page[i].new_adverts.price_from + ' - ' + page[i].new_adverts.price_to + ' р.');
				}
			} else {
				$('p.gray:eq(0)', item).html('&nbsp;');
				$('p.prise:eq(0)', item).html('&nbsp;');
			}
			//used adverts
			if (page[i].used_adverts != null) {
				if (typeof page[i].used_adverts.count != 'undefined') {
					$('p.gray:eq(1)', item).html(page[i].used_adverts.count + wordEnding(page[i].used_adverts.count, ' подержаны', 'й', 'х', 'х'));
				}
				if (typeof page[i].used_adverts.price_from != 'undefined' && typeof page[i].used_adverts.price_to != 'undefined') {
					$('p.prise:eq(1)', item).html(page[i].used_adverts.price_from + ' - ' + page[i].used_adverts.price_to + ' р.');
				}
			} else {
				$('p.gray:eq(1)', item).html('&nbsp;');
				$('p.prise:eq(1)', item).html('&nbsp;');
			}
		}
	}
}

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;
}


/**
 * Checking Email
 *
 * @param v
 */
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);
}

/**
 * Checking username
 * Only space-symbol, russian and english alphabet
 * Length range: [1-60]
 * And mustn`t inlclude 'www' or 'WWW' substr
 *
 * @param s
 */
function isUserName(s) {
	var regRus = /^([а-яА-ЯёЁ])+$/;
	var regEnglish = /^([a-zA-Z0-9\.\-_])+$/;
	var wwwreg = /(www)|(WWW)|\@/;
	return ((regRus.test(s)||regEnglish.test(s)) && (s.length > 0) && (s.length <= 60) && (!wwwreg.test(s)));
}

/**
 * Checking message
 * Length range: [1-300]
 * And mustn`t inlclude 'www' or 'WWW' substr
 *
 * @param m
 */
function isValidMessage(m) {
	var wwwreg = /(www)|(WWW)/;
	return ((!wwwreg.test(m)) && (m.length > 0) && (m.length <= 300));
}

function toggleMask(isshow) {
	if (isshow || isshow == undefined) {
		$('#popupCurtain').show();
	} else {
		$('#popupCurtain').hide();
	}
}

/**
 * Redirect to url
 * @param url
 */
function goTo(url) {
	window.location.href = url;
}

/**
 * Show error message
 * @param message
 */
function showError(message) {
	alert(message);
}

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));
}
/**
 * Show brauser box in IE6 section
 * @param
 */
function ie6_drop_func() {
	if ($('#ie6_browser_text').text() == 'Подробнее') {
		$('#ie6_browser_box').show();
		$('#ie6_browser_text').html('Свернуть');
	} else {
		$('#ie6_browser_box').hide();
		$('#ie6_browser_text').html('Подробнее');
	}
}
/**
 * Hide IE6 section and setup cookie
 * @param
 */
function ie6_close_func() {
	var exdate = new Date();
	exdate.setDate(exdate.getDate() + 14);

	$.cookie('ie6_cookie', 1, {path: '/', domain: $('#site_cookie_path').val(), expires: exdate});
	$('#ie6_browser_main_box').hide();
}

function showhideSM(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 = "ico-minus";
	}

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

	return false;
}

function processButtonFind() {
	var def = 'Введите ключевое слово, id объявления или номер телефона';
	var search = jQuery('#id_keywords');
	if ((search.val() == def || $.trim(search.val()) == '') && ($(form).attr('id') == 'filters')) {
		return false;
	}
	if ($('#only-in-cur-cat-field').length && $('#only-in-cur-cat-field').prop('checked')) {
		// leaf category or advert page
		if ($('#filter').length) {
			// leaf cat with own filter block
			if ($('#filter input[name=keywords]').length) {
				$('#filter input[name=keywords]').val( $('#id_keywords').val() );
			} else {
				$('#filter').append('<div class="filterItem rows" data-item-name="keywords" data-item-type="text">\n\
									<div class="lbl"><div class="floatLeft"> Ключевые слова &nbsp; </div></div>\n\
									<div class="hid-o"><ul><li><div class="chk-b " style="height: 20px;">\n\
									<input type="text" autocomplete="off" value="' + $('#id_keywords').val() + '" name="keywords">\n\
									</div></li></ul></div></div>');
			}
			$('#show-result-search').click();
		} else {
			// advert page
			var advert_loc = $('#advert-rubric-uri').text() + 'search/keywords=' + encodeURIComponent($('#id_keywords').val()) + '/';
			document.location.href = advert_loc;
		}
	} else {
		// not leaf and other situation
		$('#filters').submit();
	}
	return false;
}

/**
 * Multidictionary hidden
*/
function setHandlerCheckboxForMultiselect() {
		$('.multiDictionaryContainer').each(function() {
			var $multi = $(this);
			var $checks = $(':checkbox', $multi);
			var $hidden = $(':hidden', $multi);
			$checks.click(function() {
				var $checked = $(':checked', $checks.parent());
				var n = $checked.length;
				var str = '';
				for (var i = 0; i < n; i ++) {
					if (str.length) {
						str += ';';
					}
					str += $checked.eq(i).attr('val');
				}
				$hidden.val(str);
			});
		});
	};
