/**
 * event.layerX and event.layerY are broken and deprecated in WebKit
 * The temporary fix is to run this code before you do any event binding via jQuery.
 * NEED UPDATE jQuery TO 1.7
 */
(function(){
	// remove layerX and layerY
	var all = $.event.props,
	    len = all.length,
	    res = [];
	while (len--) {
	  var el = all[len];
	  if (el != 'layerX' && el != 'layerY') res.push(el);
	}
	$.event.props = res;
}());

/**
 * Функция реализует механизм классического наследования
 * с заимствованием прототипа и конструктора
 *
 * @param {Object} parent
 * @param {Object} prototype
 * @param {Object} construct если параметр не передан - заимствуется родительский конструктор
 * @return {Object}
 */
var inherit = function(parent, prototype, construct) {
	//Если нет конструктора - заимствуем
	if(typeof construct === 'undefined') {
		construct = function() {
			parent.apply(this, arguments);
		};
	}

	//Заимствованеи прототипа
	construct.prototype = $.extend({parent: parent}, parent.prototype, prototype);
	return construct;
};

Array.prototype.isEmpty = function() {
	for(var i in this) {
		if(this.hasOwnProperty(i)) {
			return false;
		}
	}
	return true;
};

String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g,"");
};

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

function failureAlert(){
	alert('Ошибка сервера, попробуйте еще раз.');
}

//----------------------------------------------------------------------------------------------------------------------

/**
* Count user ads, when userarea popup open
*/
function getUserAdsCountForUserareaPopup(userareaPopup) {
	$.popup.showActivity(userareaPopup);
	if (!$(this).data('is_loaded')) {
		$(this).data('is_loaded', 1);
		$.ajax({
			url: '/irr/ajax/get_user_ads_counter.php',
			dataType : 'json',
			success: function(data) {
				userareaPopup.find("#user_ads_counter").text(data.count);
				$.popup.hideActivity();
			},
			failure: function() {
				userareaPopup.find("#user_ads_counter").text(0);
				$.popup.hideActivity();
			}
		});
	} else {
		$.popup.hideActivity();
	}
}

/**
 * Set cookie
 * @param cookieName
 * @param cookieValue
 * @param days
 * @param path
 * @param domain
 */
function setCookie(cookieName, cookieValue, days, path, domain) {
	if (days == null || days == 0) {
		days = 1;
	}
	var exp_date = new Date();
	exp_date.setDate(exp_date.getDate() + days);

	if (path == null) {
		path = '/';
	}
	if (domain == null && $('#site_cookie_path')) {
		domain = $('#site_cookie_path').val();
	}

	$.cookie(cookieName, cookieValue, {path: path, domain: domain, expires: exp_date});
}

/**
 * Show curtain
 * @param is_show
 */
function toggleMask(is_show) {
	if (is_show || is_show == undefined) {
		$('#popupCurtain').show();
	} else {
		$('#popupCurtain').hide();
	}
}

/**
 * Check login valid
 * @param login
 */
function loginCheck(login) {
	var res = {
		valid: true,
		msg: ''
	};
	if (login.search(/[ '"<>\(\)\{\}\[\]\|!\?%№&^,\\\/=;:\$`~]/) !== -1) {
		res.valid = false;
		res.msg = 'Использование специальных символов и пробелов в логине запрещено';
		return res;
	}
	if (login.length < 4) {
		res.valid = false;
		res.msg = 'Слишком короткий логин';
		return res;
	}
	if (login.length > 50) {
		res.valid = false;
		res.msg = 'Слишком длинный логин';
		return res;
	}
	return res;
}

/**
 * Check email valid
 * @param email
 */
function emailCheck(email) {
	var res = {
		valid: true,
		msg: ''
	};
	if(!email.trim()) {
		res.valid = false;
		res.msg = 'Введите e-mail';
		return res;
	}
	if(!/^([\w\.\-])+@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/i.test(email)) {
		res.valid = false;
		res.msg = 'Вы ввели некорректный e-mail';
		return res;
	}
	return res;
}

/**
 * Check password valid
 * @param password
 */
function passwordCheck(password) {
	var res = {
		valid: true,
		msg: ''
	};
	if(password.length < 6) {
		res.valid = false;
		res.msg = 'Минимальная длина пароля 6 символов';
		return res;
	}
	if(/[^\w]/i.test(password)) {
		res.valid = false;
		res.msg = 'Пароль может содержать буквы латинского алфавита, цифры и символ "_"';
		return res;
	}
	return res;
}

/**
 * Check password confirm
 * @param passwordConfirm
 * @param password
 */
function passwordConfirmCheck(passwordConfirm, password) {
	var res = {
		valid: true,
		msg: ''
	};
	if(password != passwordConfirm) {
		res.valid = false;
		res.msg = 'Введенные пароли не совпадают';
		return res;
	}
	return res;
}

/**
 * Reset form elements to initial values
 * @param selector
 */
function resetForm(selector) {
	$(selector)[0].reset();
}

/**
 * Clear all form elements
 * @param selector
 */
function clearForm(selector) {
	$(':text, :password, :file, textarea', selector).val('');
	$(':input, select option', selector)
			.removeAttr('checked')
			.removeAttr('disabled')
			.removeAttr('selected');
	$('select', selector).prop('selectedIndex', 0);
}

/**
 * Return right world form, depending on count
 * @param i
 * @param one
 * @param two
 * @param many
 */
function wordDeclension(i, one, two, many) {
	var module100 = i % 100;
	if (module100 >= 10 && module100 < 20) {
		return many;
	}
	var modulo10 = i % 10;
	if (modulo10 == 1) {
		return one;
	}
	if (modulo10 == 2 || modulo10 == 3 || modulo10 == 4) {
		return two;
	}
	return many;
}

//----------------------------------------------------------------------------------------------------------------------

$(function() {

	/**
	 * Check user auth and get user auth info
	 */
	if($('#topBlock').length) {
		$('#topBlock').checkUserAuth();
	}

	/**
	 * Add to bookmarks
	 */
	if($('.linkAddToFavorites').length) {
		$('.linkAddToFavorites').jBrowserBookmark();
	}

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

	/**
	 * Попап сортировки
	 */
	if($('.sliderShowLink').length) {
		$('.sliderShowLink').listSlider({
			show: function($popUp, $button){
				//Позиционирование
				$popUp.css('margin-top', '-4px');
			}
		});
	}

	/**
	 * Попап выбора валюты для adlist
	 * после выбора валютта запоминается в cookies
	 */
	(function() {
		var currencies = {
			'USD': 'USD',
			'BYR': 'Руб',
			'EUR': 'EUR'
		};
		var switchCurrency = function(currency) {
			if(!currency || typeof currencies[currency] === 'undefined') {
				currency = 'USD';
			}
			$('#currencyTitlePopup').html(currencies[currency]);
			$('#currencyTitle').html(currencies[currency]);
			$('.adListTable .tdPrise .prise').hide();
			$('.adListTable .tdPrise .price' + currency).show()
		};
		switchCurrency($.cookie('price_view'));
		$('#currenciesContainer li a').click(function() {
			var currency = $(this).attr('currency');
			setCookie('price_view', currency);
			switchCurrency(currency);
		});
		if($('.showCurrenciesPopup').length) {
			$('.showCurrenciesPopup').listSlider({
				show: function($popUp, $button){
					//Позиционирование
					var offset = $popUp.offset();
					$popUp.css({
						'margin-top' : '-4px',
						'left': offset.left - 13
					});
				}
			});
		}
	})();

	/**
	 * Попап выбора категорий
	 */
	if($('#moreCategories').length) {
		$('#moreCategories').listSlider({popUpSelector: "#moreCategoriesBlock"});
	}

	/**
	 * Old browsers using notice
	 */
	if($('#old_browsers_main_box').length) {
		$('#old_browsers_main_box').oldBrowsersNotice();
	}

	/**
	 * Userarea menu popup in header
	 */
	if($('#loadUserareaMenuPopup').length) {
		$('#loadUserareaMenuPopup').listSlider({
			popUpSelector: "#userareaMenuPopup",
			show: getUserAdsCountForUserareaPopup
		});
	}

	/**
	 * Region popup
	 */
	if($('#viewRegion').length) {
		$('#viewRegion').region('#popupRegion');
	}

	/**
	 * Input data filter
	 */
	if($('input[data-filter]').length) {
		$('input[data-filter]').dataFilter();
	}

	/**
	 * Authorization, registration and password recovery popup
	 */
	if(typeof $.fn.authorizationRegistration == 'function') {
		$('body').authorizationRegistration();
	}

	//show breadcrumbs popup
	$('.breadcrumbsPopup').mouseenter(function(data) {
		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();
		}
	});


	/**
	 * Листалка картинок (с попапом) на странице объявления
	 */
	(function() {
		var $zoomBtn = $('#advertPhotoZoomBtn');
		if($zoomBtn.length) {
			var $carouselUl = $('#advertPhotoPreviewCarousel');
			$zoomBtn.imageGallery({
				imagesList: $carouselUl,
				preview: $('#advertPhotoPreview'),
				previewAttr: 'big_src',
				originAttr: 'origin_src',
				carouselSource: $carouselUl.parent().html(),
				popUp: $('#adPreviewPhoto')
			});
		}
	})();

	//Счётчик на странице объявления
	(function() {
		if(typeof detailsCount != 'undefined' && $('#viewCnt').length){
			$('#viewCnt').html(detailsCount);
		}
	})();

	//Отправить другу
	(function(){
		var $popup = $('#sendToFriendPopup');
		if(!$popup.length) {
			return;
		}
		var form = new Elements.Form($popup);
		var onSubmit = function(){
			if(form.validate()) {
				form.ajaxSubmit(function() {
					$popup.fadeOut(250);
					alert('Ваше сообщение отправлено');
				});
			}
			return false;
		};
		$('#btnSendToFriend').click(onSubmit);
		$('form', $popup).submit(onSubmit);
		if($('.lnkSendAdToFriend').length) {
			$('.lnkSendAdToFriend').click(function(){
				$.popup.close();
				$popup.fadeIn(100);
				form.getElement('captcha').buildCaptcha();
			});
		}
		if($('.closer').length) {
			$('.closer').click(function() {
				$popup.fadeOut(250);
			});
		}
	})();

	(function() {
		var $popup = $('#complainPopup');
		if(!$popup.length) {
			return;
		}
		var form = new Elements.Form($popup);
		var onSubmit = function(){
			if(form.validate()) {
				form.ajaxSubmit(function() {
					$popup.fadeOut(250);
					alert('Ваша жалоба отправлена');
				});
			}
			return false;
		};
		$('#btnSendComplaint').click(onSubmit);
		$('form', $popup).submit(onSubmit);

		if($('#btnComplainShow').length) {
			$('#btnComplainShow').click(function(){
				$.popup.close();
				$popup.fadeIn(100);
				form.getElement('captcha').buildCaptcha();
			});
		}
		if($('.closer').length) {
			$('.closer').click(function() {
				$popup.fadeOut(250);
			});
		}
	})();

	/**
	 * Ссылка в избранное/в избранном для страницы объявления
	 */
	$('#lnkAdvertToFavorites').click(function(){
		Favorites.add($(this).attr('ad_id'));
		var $parent = $(this).parent().hide();
		$parent.next().show();
	});

	Favorites.updateCounter();
	/**
	 * Показать все (страница объявления)
	 */
	$('#lnkShowAllAdvertText').click(function(){
		var $this = $(this);
		var $text = $this.prev().prev();
		$text.html($text.html() + $this.next().html());
		$this.prev().remove();
		$this.remove();
	});

	/**
	 * Листалка логотипов ИП на странице раздела
	 */
	(function() {
		var carouselUl = $('#SliderPartners');
		if(carouselUl.length) {
			carouselUl.jcarousel({
				scroll: 1
			});
		}
	})();

	/**
	 * Как найти своё объявление
	 */
	if($('#howFindAdvertToggle').length) {
		$('#howFindAdvertToggle').howFindAdvert('#howFindAdvertPopup');
	}

	/**
	 * Поиск по ключевому слову
	 */
	(function() {
		var def = 'Введите ключевое слово';
		var search = $('#searchKeyword, input#str');
		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);
				}
			}
		});
	})();
	$('#searchByKeywordButton').click(function(){
		var keyword = $("#searchKeyword").val().trim();
		if(keyword.length < 3){
			return false;
		}
		document.location = $('#sitePath').val() + '/searchads/search/keywords=' + encodeURIComponent(keyword) + '/';
	});
	$("#searchKeyword").keypress(function(e){
		if(e.which == 13) {
			$('#searchByKeywordButton').click();
			return false;
		}
	});
	if($('#showFindByKeywordPopup').length) {
		$('#showFindByKeywordPopup').listSlider({
			popUpSelector: "#findByKeywordPopup",
			show: function($popUp, $button){
				//Позиционирование
				var a_width = $button.width();
				$popUp.css('left', $button.position().left + 689 - a_width);
				$popUp.css('top', $button.position().top + 45);
			}
		});
	}
	$('#findByKeywordPopup a.findByKeywordPlace').click(function(){
		var title = $(this).text();
		var value = $(this).attr('url_val');
		$('#showFindByKeywordPopup span').text(title);
		$('#findByKeywordPopup .title span').text(title);
		$('#url').val(value);
		$('#findByKeywordPopup').hide();
		return false;
	});

	/**
	 * Карта yandex на странице объявления
	 */
	(function() {
		var $container = $('#advertMapContainer');
		if(typeof YMaps !== 'undefined' && $container.length) {
			var $hide = $('#hideAdvertMap');
			var $show = $('#showAdvertMap');

			//Показать
			$show.click(function() {
				$container.fadeIn(150);
				if(!initialized) {
					initMap();
				}
				$show.addClass('act');
				$hide.removeClass('act');
				$('.b-params').fadeOut(150);
			});

			//Спрятать
			$hide.click(function() {
				$container.fadeOut(250);
				$show.removeClass('act');
				$hide.addClass('act');
				$('.b-params').fadeIn(250);
			});

			var initialized = false;
			var initMap = function() {
				initialized = true;
				var map = new YMaps.Map($container[0]);

				// Запуск процесса геокодирования
				var geocoder = new YMaps.Geocoder($container.attr('address'), {results: 1, boundedBy: map.getBounds()});
				// Создание обработчика для успешного завершения геокодирования
				YMaps.Events.observe(geocoder, geocoder.Events.Load, function () {
					// Если объект был найден, то добавляем его на карту
					// и центрируем карту по области обзора найденного объекта
					if(this.length()) {
						var geoResult = this.get(0);
						map.addOverlay(geoResult);
						map.setBounds(geoResult.getBounds());
					}
				});

				map.addControl(new YMaps.SmallZoom());
				map.addControl(new YMaps.ToolBar());
				map.addControl(new YMaps.TypeControl());
			}
		}
	})();
});

/**
 * Поисковая статистика
 */
function getSearchStats(keywords, region_id, virtual_id) {
	if(keywords) {
		$.ajax({
			url: '/irr/ajax/lastsearch.php',
			success: function () {},
			failure: function () {},
			data: {
				kw: keywords,
				vid: virtual_id,
				rid: region_id
			}
		});
	}
	return false;
}
