$(function(){
	// определение региона нахождения пользователя
	// проверка typeof для обратной совместимости с макетами сайта, там не выставлена переменная GEO_IP_REGION_URL
	if (typeof GEO_IP_REGION_URL != 'undefined') {
		initGeoIPRegion();		
	}	
	
	var popUpLink = {
		MORE_MENU: 0
		, elements: [
		{
			link: $('#menu-link-more')
			, block: $('#menu-link-more-block')
			, place: $('#menu-link-more-place')
			, arrowOn: 'w-arrow-on'
			, placeBackGround: 'menu-link-more-title-bgr'
		}
		]
	};

	// обработка кликов по выпадающим меню
	// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
	$('#menu-link-more').click(function(){
		popUpClick(popUpLink.MORE_MENU, popUpLink);
	});

	// список городов
	initCitiesDropDown();
	
	// где купить
	initWherBuy();	
	
	// ссылка на версию предыдущего сайта
	initPrevVersion();
	
	// обработка фона страницы
	// проверка typeof для обратной совместимости с макетами сайта, там не выставлена переменная BACK_GROUND_TEMPLATE 
	if (typeof BACK_GROUND_TEMPLATE != 'undefined') {
		$('.change-bgr .inline a').click(function(){
			if (BACK_GROUND_TEMPLATE) changeBgr($(this).attr('tag'), BACK_GROUND_TEMPLATE);
		});
		if (BACK_GROUND_TEMPLATE) setBackground(BACK_GROUND_TEMPLATE);			
	}
	
	// предпросмотр для картинок и галерей
	initImageGalleries();
	
	//скрыть показать текст ссылки 
	initToggleText();
});

function popUpClick(index, popUpLink) {
	var l = popUpLink.elements[index].link,
	b = popUpLink.elements[index].block,
	p = popUpLink.elements[index].place,
	a = popUpLink.elements[index].arrowOn,
	pb = popUpLink.elements[index].placeBackGround;
	if (!l.is('.' + a)) {
		b.slideToggle('fast');
		l.toggleClass(a);
		p.toggleClass(pb);
		setTimeout(function(){
			$('body').bind('click', function() {
				if (l.is('.' + a)) {
					b.slideToggle('fast');
					l.toggleClass(a);
					p.toggleClass(pb);
					$('body').unbind('click');
				}
			});
		}, 100);
	}	
}

function initCitiesDropDown() {
	$('#city-dropdown').click(function(){
		var l = $('#dd-arw'),
		b = $('#city-list'),
		p = $('#tl-place'),
		a = 'dd-arrow-close';

		if (!l.is('.' + a)) {
			b.slideToggle('fast');
			l.toggleClass(a);
			setTimeout(function(){
				$('body').bind('click', function() {
					if (l.is('.' + a)) {
						b.slideToggle('fast');
						l.toggleClass(a);
						$('body').unbind('click');
					}
				});
			}, 100);
		}
	});
}

function isNumeric(value){	
	return ((!isNaN(value)) ? value >= 0 : false);
}

function changeCity (cityUrl) {	
	var url = "/city.html?cityUrl=" + cityUrl;	
	$.getJSON(url, function(data) {	
		var pathname = location.pathname
			, existCatalog = pathname.indexOf('/catalog') >= 0
			, action = pathname.substring(pathname.lastIndexOf('/'), pathname.length);
		if	(existCatalog) {
			action = pathname.substring(pathname.indexOf('/catalog'))
		}
		var url = location.protocol + "//" + location.host + data.cityLangPrefixUrl  + action +  location.search;
		window.location.href = url;
	});
}

function changeBgr (id, imgPath) {
	$('#randbgr').attr('background', imgPath + id +'.jpg');
	$.cookie('cookie_tez_bgr', id, { expires: 365, path: '/'});
}

	
function setBackground (imgPath) {
	// // проверка typeof для обратной совместимости с макетами сайта, там не загружается плагин с куками
	var bgrId = (typeof $.cookie != 'undefined') ? $.cookie('cookie_tez_bgr') : null,
		$bgr = $('#randbgr');
	
	if (!bgrId) {
		var random_number = Math.round(Math.random() * ($('.change-bgr .inline a').length - 1)) + 1;  
		$bgr.attr('background', imgPath + (random_number < 2 ? 2 : random_number) + '.jpg');
	} else {
		$bgr.attr('background', imgPath + bgrId + '.jpg');   
	}
} 

function initWherBuy() {
	$('#firstlevel a[href*=gdekupit], .footer-map a[href*=gdekupit]').attr('target', '_blank');
	
/*	$('#firstlevel a[href*=gdekupit], .footer-map a[href*=gdekupit]').click(function() {
		$.fancybox({			
			'padding'       : 0,
			'height'        : 500,
			'width'         : 900, 
			'titleShow'		: false,
			'type'			: 'iframe',		
			'href'          : $(this).attr('href'),	
			'transitionIn'	: 'none',
			'transitionOut'	: 'none'
		});		
		return false;
	});*/
}

function changeLang (langUrl) {	
	var url = "/index.html?langUrl=" + langUrl;	
	$.getJSON(url, function(data) {	
		var pathname = location.pathname;
		var action = pathname.substring(pathname.lastIndexOf('/'), pathname.length);
		var url = location.protocol + "//" + location.host + data.cityLangPrefixUrl  + action +  location.search;
		window.location.href = url;
	});
}

function initPrevVersion() {
	var $panel = $('#topLine .topLine-center'),
		$showPanel = (typeof $.cookie != 'undefined') ? $.cookie('cookie_tez_prev') : true;
		$showPanel = $showPanel == null ? true : eval($showPanel); 
		
	$showPanel ? $panel.show() : $panel.hide(); 
	$('a.oldvers-close', $panel).click(function() {
		$.cookie('cookie_tez_prev', false, { expires: 365, path: '/'});	
		$panel.hide(); 
		return false;
	});
	
}

function initImageGalleries() {
	if ($.isFunction($.fancybox)) {
		$('a.zoom-img').fancybox({
			'titlePosition' 	: 'over',
			'titleFormat'       : function(title, currentArray, currentIndex, currentOpts) {
				return title!="" ? '<span id="fancybox-title-over">' + title + '</span>' : '';
			}
		});
		
		var $imgTables = $('.zoom-img-group');
		$.each($imgTables, function(i, tbl) {
			$('a.zoom-img', tbl).attr('rel', i).fancybox({
				'transitionIn'		: 'none',
				'transitionOut'		: 'none',
				'titlePosition' 	: 'over',
				'titleFormat'       : function(title, currentArray, currentIndex, currentOpts) {
					return '<span id="fancybox-title-over">Image ' +  (currentIndex + 1) + ' / ' + currentArray.length + ' ' + title + '</span>';
				}
			});
		});		
	}
}

function initGeoIPRegion() {
	if ($.isFunction($.fancybox) && $.isFunction($.cookie)) {
		if 	($.cookie('tez_city') == null) {
			$.fancybox({
				'padding'        : 0,
				'scrolling'		 : 'no',
				'titleShow'		 : false,
				'href'           : '#dtctd-reg-short',
				'showCloseButton': true,
				'modal'          : false,
				'onClosed'       : function() {$.cookie('tez_city', 'msk', { expires: 365, path: '/'});}
			});
			
			$("#dtctd-reg-short a").fancybox({
				'padding'        : 0,
				'scrolling'		 : 'no',
				'titleShow'		 : false,
				'href'           : '#dtctd-reg-full',
				'showCloseButton': true,
				'modal'          : false,
				'onClosed'       : function() {$.cookie('tez_city', 'msk', { expires: 365, path: '/'});}
			});
			
			geoIpRegion();			
		}	
	}
}

function geoIpRegion() {
	$.getJSON(
		GEO_IP_REGION_URL,
		function(data) {
			var buffer = "";
			var cityUrl = "";
			for (i = 0; i < data.region.length; i++) {
				var item = data.region[i];
				cityUrl = item.urlName;
				buffer = '<div class="flag flag_'+ item.countryId +'"></div><i class="dd-city">'+item.country+', <b>'+item.city+'</b> </i>';
                
			}						
			$('#geoIpRegion').append(buffer);
			var buttonText = '<input onclick="changeCity(\''+ cityUrl +'\')" id="changeCity" name="submit" type="submit" value="Да, всё верно" class="dtctd-reg-login-butt">';
			$('#submitButton').append(buttonText);
	 });
}

	
function initToggleText() {	
	$('a.b-dotted.toggleText').click(function() {
		$(this).text($(this).text() == TOGGLE_HIDE_BLOCK ? TOGGLE_SHOW_BLOCK : TOGGLE_HIDE_BLOCK);
		$('#'+ ($(this).attr('tag'))).toggle();
	});
}  

