function isiPhone(){
    return (
        (navigator.platform.indexOf("iPhone") != -1) ||
        (navigator.platform.indexOf("iPod") != -1)
    );
}


function web_analitycs(name, param)
{
	window._gaq.push(['_trackEvent', name, param]);
}


function share_gameresult(sn, time, type)
{
	if (type == '4x4') type = 'offroad';

	var title = 'Шины DUNLOP готовы к любым поворотам!';
	var text = 'Я проехал трассу на шинах DUNLOP всего за ' + time + '! Сможешь проехать быстрее?';
	var gurl = 'http://www.dunlop-tire.ru/#opengame;' + type;
	var pic = 'http://www.dunlop-tire.ru/@/fit/share_' + type + '.jpg';

	switch (sn)
	{
		case 'fb':

			url  = 'http://www.facebook.com/sharer.php?s=100';
			url += '&p[title]='     + encodeURIComponent(title);
			url += '&p[summary]='   + encodeURIComponent(text);
			url += '&p[url]='       + encodeURIComponent(gurl);
			url += '&p[images][0]=' + encodeURIComponent(pic);

			break;

		case 'tw':

			url  = 'http://twitter.com/share?';
			url += 'text='      + encodeURIComponent(text);
			url += '&url='      + encodeURIComponent(gurl);
			url += '&counturl=' + encodeURIComponent(gurl);

			break;

		case 'vk':

			url  = 'http://vkontakte.ru/share.php?';
			url += 'url='          + encodeURIComponent(gurl);
			url += '&title='       + encodeURIComponent(title);
			url += '&description=' + encodeURIComponent(text);
			url += '&image='       + encodeURIComponent(pic);
			url += '&noparse=true';

			break;

	}
		
	window.open(url,'','toolbar=0,status=0,width=626,height=436');

}

function openGame(game_type) {

	var bg = $q('#game-bg'),
		homepageNav = $q('#homepage-nav'),
		gameWindow = $q('#game-window'),
		game = $q('#game-window div.game');

	if ($q(window).height() < 800) {
		homepageNav.css('marginTop','427px');
	} else {
		homepageNav.css('marginTop','535px');
	}

	bg.css('display','block').css('opacity','0').animate({opacity: '.9'}, 150);
	gameWindow.css('display','block').css('opacity','0').animate({opacity: '1'}, 350, 
	
		function () {

			web_analitycs ('game.open', game_type);
			
			var flashvars = {
				vehicletype: game_type
			};
			
			var params = {
				bgcolor: "#000000",
				wmode: "window",
				scale: "noscale",
				allowscriptaccess: "always",
				allowfullscreen: true,
				base: "/files/game/"
			};
			
			var attributes = {
				id: "flash_game",
				name: "flash_game"
			};

			if (!isiPhone() && swfobject.hasFlashPlayerVersion('10.2'))
			{
				$q('.window .flash').show();
				swfobject.embedSWF("/files/game/Main.swf", "flash_game", "100%", "100%", "10.2", "/files/game/expressInstall.swf", flashvars, params, attributes);
			}
			else
			{
				$q('.noflash').show();
				
			}

		}
	);

}

(function ($)
{
	$.fn.hint = function (blurClass)
	{
	    if (!blurClass) blurClass = 'blur';
	
	    return this.each(function () {
	        var $input = $(this),
	            title = $input.attr('title'),
	            $form = $(this.form),
	            $win = $(window);
	
	        function remove() {
	            if (this.value === title && $input.hasClass(blurClass)) {
	                $input.val('').removeClass(blurClass);
	            }
	        }
	
	        // only apply logic if the element has the attribute
	        if (title) {
	            // on blur, set value to title attr if text is blank
	            $input.blur(function () {
	                if (this.value === '') {
	                    $input.val(title).addClass(blurClass);
	                }
	            }).focus(remove).blur(); // now change all inputs to title
	
	            // clear the pre-defined text when form is submitted
	            $form.submit(remove);
	            $win.unload(remove); // handles Firefox's autocomplete
	        }
	    });
	};
})(jQuery);

(function($) {
	$.fn.gmapDealer = function(options) {
		var map,
			mapPosX,
			mapPosY,
			gCollection = new YMaps.GeoObjectCollection(),
			currentBounds,
			gCollectionSearch = new YMaps.GeoObjectCollection(),

			target = $(this),
			searchField = $('#'+options.searchFieldId),
			searchFieldBtn = $('#'+options.searchFieldBtnId),
			coordinateField = $('#'+options.coordinateFieldId),
			regionList = $('#dealer-regions ul'),
			dealerList = $('#dealers'),
			slideMapBtn = $('a.map-slide')
			curPlaceBtn = $('#cur-place');

		mapInit();
		markersSet();
		mapSliderInit();
		searchInit();
		regionListInit();
		dealerListInit();

		function mapInit() {
			map = new YMaps.Map(document.getElementById(target.attr('id')));
			map.setType(YMaps.MapType.MAP);
			
			var geocoder = new YMaps.Geocoder(regionList.find('a.clicked').attr('rel'), {results: 1});// Запуск процесса геокодирования
			
			YMaps.Events.observe(geocoder, geocoder.Events.Load, function () { 
				if (this.length())
				currentBounds=this.get(0).getBounds();
			});
			
			map.addControl(new YMaps.TypeControl());
			map.addControl(new YMaps.ToolBar());
			map.addControl(new YMaps.Zoom());
			map.addControl(new YMaps.ScaleLine());
			map.addOverlay(gCollection);
			map.addOverlay(gCollectionSearch);
		}
		
		function markersSet() {
			dealerList.find('td').each(function() {
				var mapHref = $(this).children('a.show-on-map');

				if (!mapHref.length) 
					return;

				var coord = mapHref.attr('rel').split(';');

				var dealer = $(this).clone();
//				dealer.children('a.show-on-map, a.email, a.web').remove();
				dealer.children('a.show-on-map').remove();
				
				createMarker(coord[1],coord[0],dealer.html());
				
				mapHref.attr('rev',gCollection.length()-1);
			});
			
			// Создаем область показа по группе точек
			var points=[];
			
			for (var k=gCollection.length()-1; k>=0; k--)
			points.push(gCollection.get(k).getGeoPoint());
			
    		var bounds = new YMaps.GeoCollectionBounds(points);
			map.setBounds(bounds);
			if (map.getZoom()>10) map.setZoom(10);
			
			if (!currentBounds) currentBounds=map.getBounds();	//если вдруг что-то автоматом не поставилось
		}
		
		function mapSliderInit() {
			slideMapBtn.bind('click', function(e){
				e.preventDefault();
				mapSliderShow2(slideMapBtn.hasClass('opened'));
				return true;
			});
			
			curPlaceBtn.bind('click', function(e){
				e.preventDefault();
				mapSliderShow(curPlaceBtn.hasClass('opened'));
				return true;
			});	
		}
		
		function mapSliderShow2(hide)
		{
			var mapBox = $('#gmap-dealer'),
				animationSpeed = 700;
				
			if (hide) {
				mapBox.slideUp(animationSpeed, function(){
					slideMapBtn.text('Развернуть карту').toggleClass('opened');
				});
			} else {
				mapBox.slideDown(animationSpeed, function(){
					slideMapBtn .text('Свернуть карту').toggleClass('opened');
					map.redraw();//избавление от бага, когда ресайзается окно браузера при закрытой карте и она ломается при открытии
				});
			}
		}
		function mapSliderShow(hide)
		{
			var list = $('#dealer-regions ul'),
				animationSpeed = 700;
				
			if (hide) {
				list.slideUp(animationSpeed, function(){
					curPlaceBtn.toggleClass('opened');
				});
			} else {
				list.slideDown(animationSpeed, function(){
					curPlaceBtn.toggleClass('opened');
					map.redraw();//избавление от бага, когда ресайзается окно браузера при закрытой карте и она ломается при открытии
				});
			}
			
			return true;
		}

		function searchInit() {
			var geoResult;
		
			searchField.autocomplete({
				source: function(request, response) {
					var reg = $(regionList).find('li a.clicked').attr('rel');
					var region = reg; 
					reg = reg.split(',');
					var city = reg[1].replace(/^\s*город\s+/,'');
					
					if (city!=reg[1])
					reg.splice(0,0,city);
					
					var geocoder = new YMaps.Geocoder(region  + ', ' + request.term, {strictBounds:1, boundedBy: currentBounds});// Запуск процесса геокодирования
					
					YMaps.Events.observe(geocoder, geocoder.Events.Load, function () { // Создание обработчика для успешного завершения геокодирования
						response($.map(this._objects, function(item) {
							var str='',param,val = item.text.split(',');
							
							for (var k=0;k<val.length;k++)
							{
								for (var i=0;i<reg.length;i++)
								{
									var regx = new RegExp('\s*'+reg[i]+'\s*');
									param = regx.exec(val[k]);
									if (param) break;
								}
								
								if (param) continue;
								if (str) str+=',';
								str += val[k];
							}
							return {
								label: str,
								value: str,
								latitude: item._point.__lat,
								longitude: item._point.__lng
							}
						}));
					});
				}
			});
			
			searchFieldBtn.parent().parent().bind('submit', function(e) {
				e.preventDefault();
				
				if (!searchField.val())
					return;
				
				if (!slideMapBtn.hasClass('opened')) 
				mapSliderShow2(false);
				
				gCollectionSearch.removeAll();
				var region = $(regionList).find('li a.clicked').attr('rel') + ', ';
				var geocoder = new YMaps.Geocoder(region + searchField.val(), {strictBounds:1, results: 1, boundedBy: currentBounds});// Запуск процесса геокодирования
				
				YMaps.Events.observe(geocoder, geocoder.Events.Load, function () { 
					if (this.length()) { 
						geoResult = this.get(0);
						point = new YMaps.GeoPoint(geoResult._point.__lng, geoResult._point.__lat);
						
						var address = this.get(0).text;
						geoResult.setBalloonContent('<p>' + address + '</p>');
						gCollectionSearch.removeAll();
						gCollectionSearch.add(geoResult);
						
						var points=[], len=[], tmp, i,num;
						for (var k=gCollection.length()-1; k>=0; k--)
						{
							tmp = point.distance(gCollection.get(k).getGeoPoint());
							for (i=0,num=len.length;i<num;i++)
							{
								if (len[i]<tmp) continue;
								
								len.splice(i,0,tmp);
								points.splice(i,0,gCollection.get(k).getGeoPoint());
								break;
							}
							
							if (i==num)
							{
								len.push(tmp);
								points.push(gCollection.get(k).getGeoPoint());
							}
						}
						
						points=points.slice(0,2);
						points.push(point);
						
						var bounds = new YMaps.GeoCollectionBounds(points);
						map.setBounds(bounds);
						
						//map.setZoom(map.getZoom()-1);
						geoResult.openBalloon();
					}
				});
					
				return true;
			});
		}
		
		function regionListInit() {
			regionList.find('li a').bind('click',function(e){ 
				e.preventDefault();
			
				var oThis = $(this),
					geoResult,
					coord = $(this).attr('rel');
				
				//map.removeOverlay(geoResult);
				gCollection.removeAll();
				gCollectionSearch.removeAll();
				searchField.val('');
				
				var geocoder = new YMaps.Geocoder(coord, {results: 1});// Запуск процесса геокодирования
				
				YMaps.Events.observe(geocoder, geocoder.Events.Load, function () {       // Создание обработчика для успешного завершения геокодирования
					if (this.length()) { // Если объект был найден, то добавляем его на карту и центрируем карту по области обзора найденного объекта
						mapSliderShow2(false);
						currentBounds = this.get(0).getBounds();
						
						if (!gCollection.length())
						map.setBounds(currentBounds);
						
						mapSliderShow(1);
					}
				});

				YMaps.Events.observe(geocoder, geocoder.Events.Fault, function (geocoder, error) { // Процесс геокодирования завершен неудачно
					console.log("Произошла ошибка: " + error);
				});
				
				$(regionList).find('li a.clicked').removeClass('clicked');	//по-выделенному ищем в форме поиска
				$(this).addClass('clicked');
				
				$q(QueryLoader.loadAmt).html('0%');
				$q(QueryLoader.overlay).fadeIn(800);
				$q(QueryLoader.loadBar).css({width: '0%'});
				$q(dealerList).empty();
				
				AC.simple('','POST',{'submit_dealers':true,s_region:coord},function(text)
				{
					$q(dealerList).html(text);
					markersSet();
					
					$q(QueryLoader.loadAmt).html('100%');
					$q(QueryLoader.loadBar).animate({
						width: '100%'
						}, 500, 'linear', function() { 
							QueryLoader.doneLoad();
					});
				});
				
				curPlaceBtn.html($(this).text()+'<i>&nbsp;</i>');
			
				return true;
			});
		}
		
		function dealerListInit() {
			dealerList.find('td a.show-on-map').live('click',function(e){
				e.preventDefault();
				
				if (!slideMapBtn.hasClass('opened')) 
					mapSliderShow2(false);
					
				var scrollTarget = $('#wrapper-wide');
      
				if ($(window).scrollTop() > scrollTarget.offset().top) {
					$('html, body').stop().animate({ scrollTop: scrollTarget.offset().top }, 1000);
				}
			
				var placemarkId = $(this).attr('rev'),
					placemark = gCollection.get(placemarkId),
					point = placemark.getGeoPoint();
				
				placemark.openBalloon();

				map.setCenter(point);
				map.setZoom(15);
				
				return true;
			});
		}
		
		function createMarker(posX, posY, infoboxHtml) {
			point = new YMaps.GeoPoint(posX, posY);
		
			var sampleBalloonTemplate = new YMaps.LayoutTemplate(SampleBalloonLayout);
			var style = new YMaps.Style();
			
			style.iconStyle = new YMaps.IconStyle();
			style.iconStyle.href = "/@/fit/pic-gmap-marker.png";
			style.iconStyle.size = new YMaps.Point(53, 36);
			style.iconStyle.offset = new YMaps.Point(-18, -33);
			
			style.balloonStyle = {template: sampleBalloonTemplate};

			var placemark = new YMaps.Placemark(point, {style: style, hasHint: false});
			placemark.setBalloonContent(infoboxHtml);
			gCollection.add(placemark);
			
			function SampleBalloonLayout() {
				this.element = YMaps.jQuery("<div class='infoBox'> <a class='close'></a> <div class='content'></div> </div>");
			 
				this.close = this.element.find(".close");
				this.content = this.element.find(".content");
			 
				// Отключает кнопку закрытия балуна
				this.disableClose = function(){
					this.close.unbind("click").css("display", "none");
				};
							
				// Включает кнопку закрытия балуна
				this.enableClose = function(callback){
					this.close.bind("click", callback).css("display", "");
					return false;
				};
			 
				// Добавляет макет на страницу
				this.onAddToParent = function (parentNode) {
					YMaps.jQuery(parentNode).append(this.element);
					this.update();

				};
			 
				// Удаляет макет со страницы
				this.onRemoveFromParent = function () {
					this.element.remove();
				};
			 
				// Устанавливает содержимое балуна
				this.setContent = function (content) {
					content.onAddToParent(this.content[0]);
				};
				
				// Обновляет балун
				this.update = function() {
					this.element.css("margin", '-194px 0 0 -15px');
				};
			};
		}

	};
	
	$.fn.gmapContact = function() {
		var map,
			mapPosX = 55.728,
			mapPosY = 37.44955,
			point;

		var target = $(this);

		if ($(window).height() > 800 ) target.css('height','600px');
		
		map = new YMaps.Map(document.getElementById(target.attr('id')));
		point = new YMaps.GeoPoint(mapPosY, mapPosX);
		
		map.setCenter(point, 16, YMaps.MapType.MAP);
		
		map.addControl(new YMaps.TypeControl());
		map.addControl(new YMaps.ToolBar());
		map.addControl(new YMaps.Zoom());
		map.addControl(new YMaps.ScaleLine());

		var s = new YMaps.Style();
		s.iconStyle = new YMaps.IconStyle();
		
		s.iconStyle.href = "/@/fit/pic-gmap-marker-contact.png";
		s.iconStyle.size = new YMaps.Point(123, 84);
		s.iconStyle.offset = new YMaps.Point(-40, -78);
		
		var placemark = new YMaps.Placemark(point, {style: s, hasBalloon: false, hasHint: false});
		map.addOverlay(placemark);
	};
	
	$.fn.vacancySlider = function(options) {
		var settings = {speed: 1200};
		$.extend(settings,options);

		var target = $(this),
			lis = $(this).children('li'),
			hrefs = target.find('li h2 a');
		
		hrefs.bind('click', function(e) {
			e.preventDefault();
			
			var closedDiv = $(this).parent().next();
		
			if ( closedDiv.is(':visible') ) {
				closedDiv.slideToggle(settings.speed);
			} else {
				var li = $(this).parent().parent();
				var openedDiv = lis.children('div:visible');

				openedDiv.slideToggle(settings.speed);
				closedDiv.slideToggle(settings.speed);
			}

			return true;
		});
	};
	
	$.fn.formValidate = function(options) {
		var form = $(this),
			ps = form.children('p'),
			messageBars = ps.children('span'),
			sendBtn = form.find('p.send input'),
			emailVerifyPattern = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i,
			sign = false,
			speed = 600;
		
		form.bind('submit',function() {
			ps.removeClass('error');
			messageBars.css('display','none');
			sign = false;
			
			if ( $('.email').length && !emailVerifyPattern.test( $('.email').val() ) ) {
				setError($('.email'),'Email указан не верно. Пожалуйста, повторите ввод');
				sign = true;
			}

			if ( $('.required').length ) {
				$('.required').each(function() {
					if ( !$(this).val() ) {
						setError($(this),'Поле обязательно для заполнения');
						sign = true;
					}
				});
			}
			
			if (sign) 
				return false;

			sendBtn.addClass('clicked');

			/*$.ajax({
				url: '',
				data: form.serializeArray(),
				type: 'POST', 
				dataType: 'json',
				error: function(XHR) {
				},
				success: function(data, status) {
				}
			});*/
			
			//return true;
		});
		
		function setError(input, message) {
			var p = input.parent(),
				messageBar = input.next();

			p.addClass('error');
			messageBar.text(message).fadeIn(speed);
		}
	};
	
	$.fn.catalog = function(options) {
		var settings = {speed: 350};
		$.extend(settings,options);

		var filter1 = $('#catalog-filter ul.filters'),
			titles = filter1.find('label')
			tips = titles.children('span'),
			tipShowHref = filter1.find('a.tip'),
			tipHideHref = filter1.find('label span a.close');
		
		tipShowHref.bind('click', function(e) {
			e.preventDefault();
			openedTips = tips.filter(':visible');
			
			openedTips.fadeOut(settings.speed).parent().css('zIndex', 1);
			
			if (!$(this).next().is(':visible')) {
				$(this).parent().css('zIndex', 5);
				$(this).next().fadeIn(settings.speed);
			}
			
			return true;
		});	
		
		tipHideHref.bind('click', function(e) {
			e.preventDefault();
			
			var oThis = $(this);
			oThis.parent().fadeOut(settings.speed, function(){
				oThis.parent().parent().css('zIndex', 1);
			});
			
			return true;
		});

		var filter2 = $('#catalog-filter div.selector2'),
			hrefs = filter2.children('a'),
			subMenu = filter2.find('div.sub-menu-wrap div'),
			subHrefs = filter2.find('div a');
		
		hrefs.bind('click', function(e) {
			//e.preventDefault();
			
			if ($(this).hasClass('active'))
				return false;
			
			var index = $(this).index();

			hrefs.removeClass('active');
			$(this).addClass('active');
			
			if (index == 2) {
				subMenu.addClass('opened').animate({left: '222px'},settings.speed);
			} else {
				if (subMenu.hasClass('opened'))
					subMenu.removeClass('opened').animate({left: '-60px'},settings.speed);
			}
			
			return true;
		});
		
		subHrefs.bind('click', function(e) {
			//e.preventDefault();
			
			if ($(this).hasClass('active'))
				return false;
			
			subHrefs.removeClass('active');
			$(this).addClass('active');
			
			return true;
		});
		
		var catalog = $('#catalog-body'),
			moreHrefs = catalog.find('ul li > a');
			closeHrefs = catalog.find('ul li div.tire-baloon a.close');
		
		if (moreHrefs.length)
		{
			moreHrefs.bind('click', function(e) {
				e.preventDefault();
				
				var baloon = $(this).next();
				baloon.fadeIn(settings.speed);	
				
				return true;
			});
	
			closeHrefs.bind('click', function(e) {
				e.preventDefault();
				
				var baloon = $(this).parent();
				baloon.fadeOut(settings.speed);	
				
				return true;
			});
		}
	};
	
	$.fn.catalogFilterSlider = function() {
		var scrollPanes = $(this).find('div.scroll-pane');

		scrollPanes.each(function(){
			var hrefs = $(this).children('a');
			
			if (!$(this).hasClass('speed'))
				$(this).jScrollPane({verticalDragMinHeight: 46, verticalDragMaxHeight: 46});
		
		hrefs.bind('click',function(e){
				e.preventDefault();
			
			$(this).siblings().removeClass('selected');
			$(this).toggleClass('selected');
		})
		});
	};
	
	$.fn.sizeguideAnimate = function(options) {
		var settings = {speed: 1200};
		$.extend(settings,options);

		var target = $(this),
			hrefs = target.find('div a');
			
		hrefs.children('span').css('opacity', '.4');
		
		hrefs.bind('hover', function(e) { e.preventDefault(); })
		.hover(
		  function () {
			$(this).children('span').animate({opacity: '1'}, 400);
		  },
		  function () {
			$(this).children('span').animate({opacity: '.4'}, 400);
		  }
		);
	};
	
	$.fn.sizeguideSlider = function(options) {
		$(this).smoothDivScroll({
			mouseDownSpeedBooster: '2',
			visibleHotSpots: 'onstart',
			hotSpotsVisibleTime: 1000000
		});
	};
	
	$.fn.homepageSlider = function(options) { 
		var settings = {speed: 600};
		$.extend(settings,options);

		var target = $(this),
			blocks = target.children('div.slide'),
			car = blocks.filter('.car'),
			moto = blocks.filter('.moto'),
			offroad = blocks.filter('.offroad'),
			windowWidth,
			curBlock = '',
			sign = true,
			isSmall = false,
		
			blockWidthAbs,
			blockActiveWidthAbs,
			blockInactiveWidthAbs,

			carLeft,
			carLeftActive,
			carLeftInactive,

			motoLeft = blockWidthAbs,
			motoLeftActive = blockWidthAbs,
			motoLeftInactive = blockActiveWidthAbs,
			
			offroadLeft = blockWidthAbs,
			offroadLeftActive = blockInactiveWidthAbs,
			offroadLeftInactive = blockActiveWidthAbs + blockInactiveWidthAbs,
			
			isIE = $.browser.msie && $.browser.version < 9 ? true : false,
			carLabel = car.find('div.label'),
			baseCarLabelLeft,
			inactiveCarLabelLeft,
			motoLabel = moto.find('div.label'),
			baseMotoLabelLeft,
			inactiveMotoLabelLeft,
			offroadLabel = offroad.find('div.label'),
			baseOffroadLabelLeft,
			inactiveOffroadLabelLeft;

		blocks.find('div.label').css('opacity','0');

		fitSize();

		$(window).bind('resize', function() {
			fitSize();
		});
		
		$('a.share').bind('click', function(e){
			e.preventDefault();
			
			share_gameresult($(this).attr('rel'), '123', 'moto');
			
			return false;
	
		
		});
		$('a.play_me, a.play').bind('click', function(e){
			e.preventDefault();
		
			var game_type = $(this).attr('rel');
			
			openGame (game_type);

			return false;
		});
		
		function fitSize() {
			windowWidth = parseInt($(window).width());
			
			var gameWindow = $('#game-window'),
				homepageNav = $('#homepage-nav');
						
			gameWindow.css('top', ($(window).height() < 800) ? '5px' : '65px').css('height', $('body').height())
			
			if ($(window).height() < 800) {
				homepageNav.css('marginTop','420px');
			} else {
				homepageNav.css('marginTop','535px');
			}
			
		if (windowWidth > 1340) {
				car.children('div.bg').css('background', "url('/@/fit/bg-index-car.jpg') 0 0 no-repeat");
				moto.css('background', "url('/@/fit/bg-index-moto.png') 0 0 no-repeat");
				offroad.css('background', "url('/@/fit/bg-index-offroad.png') 0 0 no-repeat");
					
				moto.children('div.bg3').css('background', "url('/@/fit/bg-index-moto.jpg') 0 0 no-repeat");
				offroad.children('div.bg3').css('background', "url('/@/fit/bg-index-offroad.jpg') 0 0 no-repeat");
			
				if (windowWidth > 1800) {
					carLeft = 0,
					carLeftActive = 0,
					carLeftInactive = 0,
			
					motoLeft = '33.3333%',
					motoLeftActive = '25%',
					motoLeftInactive = '50%',
			
					offroadLeft = '66.66666%',
					offroadLeftActive = '50%',
					offroadLeftInactive = '75%';
					
					car.find('div.label').css('marginLeft','525px');
					moto.find('div.label').css('marginLeft','450px');
					offroad.find('div.label').css('marginLeft','465px');
			} else { 
					blockWidthAbs = windowWidth * 0.3333,
					blockActiveWidthAbs = 670,
					blockInactiveWidthAbs = (windowWidth-670)/2,

					carLeft = 0,
					carLeftActive = 0,
					carLeftInactive = 0,
					
					motoLeft = blockWidthAbs+80,
					motoLeftActive = blockWidthAbs-80,
					motoLeftInactive = blockActiveWidthAbs+220,
					
					offroadLeft = blockWidthAbs*2+60,
					offroadLeftActive = blockInactiveWidthAbs*2-20,
					offroadLeftInactive = blockActiveWidthAbs + blockInactiveWidthAbs+160;
					
				car.find('div.label').css('marginLeft','505px');
					moto.find('div.label').css('marginLeft','420px');
				offroad.find('div.label').css('marginLeft','435px');
			}
			} else {
				car.children('div.bg').css('background', "url('/@/fit/bg-index-car-small.jpg') 0 0 no-repeat");
				moto.css('background', "url('/@/fit/bg-index-moto-small.png') 0 0 no-repeat");
				offroad.css('background', "url('/@/fit/bg-index-offroad-small.png') 0 0 no-repeat");
				
				moto.children('div.bg3').css('background', 'none');
				offroad.children('div.bg3').css('background', 'none');
				
			if (windowWidth > 1200) { 
					blockWidthAbs = windowWidth * 0.3333,
					blockActiveWidthAbs = 670,
					blockInactiveWidthAbs = (windowWidth-670)/2,
					
					carLeft = 0,
					carLeftActive = 0,
					carLeftInactive = 0,
					
					motoLeft = blockWidthAbs+40,
					motoLeftActive = blockWidthAbs-120,
					motoLeftInactive = blockActiveWidthAbs+140,
					
					offroadLeft = blockWidthAbs*2+60,
					offroadLeftActive = blockInactiveWidthAbs*2-20,
					offroadLeftInactive = blockActiveWidthAbs + blockInactiveWidthAbs+120;

				car.find('div.label').css('marginLeft','414px');
				moto.find('div.label').css('marginLeft','335px');
				offroad.find('div.label').css('marginLeft','340px');
			} else {
					blockWidthAbs = windowWidth * 0.3333,
					blockActiveWidthAbs = 670,
					blockInactiveWidthAbs = (windowWidth-670)/2,

					carLeft = 0,
					carLeftActive = 0,
					carLeftInactive = 0,

					motoLeft = blockWidthAbs+40,
					motoLeftActive = blockWidthAbs-120,
					motoLeftInactive = blockActiveWidthAbs+40,
			
					offroadLeft = blockWidthAbs*2+60,
					offroadLeftActive = blockInactiveWidthAbs*2+110,
					offroadLeftInactive = blockActiveWidthAbs + blockInactiveWidthAbs+80;

				car.find('div.label').css('marginLeft','400px');
				moto.find('div.label').css('marginLeft','315px');
				offroad.find('div.label').css('marginLeft','310px');
		
					isSmall = true;
			}
		}

			car.css('left', carLeft);
			moto.css('left', motoLeft);
			offroad.css('left', offroadLeft);
		
			if (isIE) {
				baseCarLabelLeft = parseInt(carLabel.css('marginLeft')),
				inactiveCarLabelLeft = baseCarLabelLeft + 180;
				
				carLabel.css('opacity', '1').addClass('visible').css('marginLeft', inactiveCarLabelLeft);
				
				baseMotoLabelLeft = parseInt(motoLabel.css('marginLeft')),
				inactiveMotoLabelLeft = baseMotoLabelLeft + 240;
				
				motoLabel.css('opacity', '1').addClass('visible').css('marginLeft', inactiveMotoLabelLeft);
				
				baseOffroadLabelLeft = parseInt(offroadLabel.css('marginLeft')),
				inactiveOffroadLabelLeft = baseOffroadLabelLeft + 240;
				
				offroadLabel.css('opacity', '1').addClass('visible').css('marginLeft', inactiveOffroadLabelLeft);
			}
		}

		blocks.fadeIn(0);

		car.children('div.bg').hover(
			function () {
				curBlock = $(this).attr('rel');
				if (sign)
					carOpen();
				else
					sign = true;
			}
		);

		moto.children('div.bg').hover(
			function () {
				curBlock = $(this).attr('rel');
				if (sign)
					motoOpen();
				else
					sign = true;
			}
		);
		
		moto.children('div.bg2').hover(
			function () {
				if ( curBlock=='moto' ) {
					carOpen();
					curBlock = '';
					sign = false;
				}
			}
		);

		offroad.children('div.bg').hover(
			function () {
				curBlock = $(this).attr('rel');
				if (sign)
					offroadOpen();
				else
					sign = true;
			}
		);
		
		offroad.children('div.bg2').hover(
			function () {
				if ( curBlock=='offroad' ) {
					motoOpen();
					curBlock = '';
					sign = false;
				}
			}
		);
		
		$('#homepage-slider-wrap').hover(
			function () {
			},
			function () {
				slideBlur();
			}
		);
		
		function carOpen() {
			blocks.find('div.label.active:not(.visible)').stop().animate({opacity: '0', queue: false}, settings.speed ).removeClass('active');
			car.stop().animate({left: carLeftActive, queue: false}, settings.speed ).find('div.label').stop().animate({opacity: '1', queue: false}, settings.speed ).addClass('active');
			moto.stop().animate({left: motoLeftInactive, queue: false}, settings.speed );
			offroad.stop().animate({left: offroadLeftInactive, queue: false}, settings.speed );
			if (isSmall)
				car.find('div.bg').stop().animate({left: '-75px', queue: false}, settings.speed );
			if (isIE) {
				carLabel.stop().animate({marginLeft: baseCarLabelLeft, queue: false}, settings.speed ); 
				motoLabel.stop().animate({marginLeft: inactiveMotoLabelLeft, queue: false}, settings.speed );
				offroadLabel.stop().animate({marginLeft: inactiveOffroadLabelLeft, queue: false}, settings.speed );
			}
		}
		
		function motoOpen() {
			blocks.find('div.label.active:not(.visible)').stop().animate({opacity: '0', queue: false}, settings.speed ).removeClass('active');
			car.stop().animate({left: carLeftInactive, queue: false}, settings.speed );
			moto.stop().animate({left: motoLeftActive, queue: false}, settings.speed ).find('div.label').stop().animate({opacity: '1', queue: false}, settings.speed ).addClass('active');
			offroad.stop().animate({left: offroadLeftInactive, queue: false}, settings.speed );
			if (isSmall)
				car.find('div.bg').stop().animate({left: '0', queue: false}, settings.speed );
			if (isIE) {
				carLabel.stop().animate({marginLeft: inactiveCarLabelLeft, queue: false}, settings.speed );
				motoLabel.stop().animate({marginLeft: baseMotoLabelLeft, queue: false}, settings.speed );
				offroadLabel.stop().animate({marginLeft: inactiveOffroadLabelLeft, queue: false}, settings.speed );
			}
		}
		
		function offroadOpen() {
			blocks.find('div.label.active:not(.visible)').stop().animate({opacity: '0', queue: false}, settings.speed ).removeClass('active');
			car.stop().animate({left: carLeftInactive, queue: false}, settings.speed );
			moto.stop().animate({left: motoLeftActive, queue: false}, settings.speed );
			offroad.stop().animate({left: offroadLeftActive, queue: false}, settings.speed ).find('div.label').stop().animate({opacity: '1', queue: false}, settings.speed ).addClass('active');
			if (isSmall)
				car.find('div.bg').stop().animate({left: '0', queue: false}, settings.speed );
			if (isIE) {
				carLabel.stop().animate({marginLeft: inactiveCarLabelLeft, queue: false}, settings.speed );
				motoLabel.stop().animate({marginLeft: inactiveMotoLabelLeft, queue: false}, settings.speed );
				offroadLabel.stop().animate({marginLeft: baseOffroadLabelLeft, queue: false}, settings.speed );
			}
		}
		
		function slideBlur() {
			car.stop().animate({left: carLeft, queue: false}, settings.speed );
			moto.stop().animate({left: motoLeft, queue: false}, settings.speed );
			offroad.stop().animate({left: offroadLeft, queue: false}, settings.speed );
			blocks.find('div.label.active:not(.visible)').stop().animate({opacity: '0', queue: false}, settings.speed ).removeClass('active');
			if (isSmall)
				car.find('div.bg').stop().animate({left: '0', queue: false}, settings.speed );
			if (isIE) {
				carLabel.stop().animate({marginLeft: inactiveCarLabelLeft, queue: false}, settings.speed );
				motoLabel.stop().animate({marginLeft: inactiveMotoLabelLeft, queue: false}, settings.speed );
				offroadLabel.stop().animate({marginLeft: inactiveOffroadLabelLeft, queue: false}, settings.speed );
			}
		}
	};
	
	$.fn.catalogModelBaloon = function(options) {
		var settings = {speed: 250};
		$.extend(settings,options);

		var target = $(this),
			lis = target.find('li');
			narrow = $(window).width() < 1100 ? true : false;

		lis.bind('hover', function(e) { e.preventDefault(); })
		.hover(
			function () {
				if ($.browser.msie && $.browser.version == 7)
					$(this).css('zIndex','10');
			
				var index = $(this).index(),
					header = $(this).children('h3'),
					baloon = $(this).children('div.tire-baloon');

				if (narrow && index%5 == 0)
					baloon.css('left','-15px');
				if (narrow && index%5 == 4)
					baloon.css('left','-90px');
				
				header.animate({opacity: '0'}, settings.speed);
				baloon.fadeIn(settings.speed);
			},
			function () {
				var baloon = $(this).children('div.tire-baloon'),
					header = $(this).children('h3');
					
				header.animate({opacity: '1'}, settings.speed);
				
					if ($.browser.msie && $.browser.version == 7)
					$(this).css('zIndex','0');
				
				baloon.fadeOut(settings.speed);
			}
		);
	};
	
	$.fn.historySlider = function(options) {
		var settings = {slideSpeed: 800};
		$.extend(settings,options);
	
		var target = $(this),
			sausage = $('#history-slider div.sausage'),
			yearRefs = $('.paging a'),
			wheel = $('#wheel'),
			wheelDiv = $('#wheel div'),
			wheelShadow = $('#wheel i'),
			yearBtn = $('.paging div'),
			yearBtnNumber = yearBtn.children('span'),
			yearBtnStep = 109,
			yearBtnSpeed = 109,

			wheelSize = 362,
			wheelPos,
			wheelRotationCounter = 0,
			newWheelRotationCounter = 0,
			wheelNumber = 0,
			wheelTrueNumber,
		
			direction,
			stepCount = 0,
			leftStepCount = 0,
			slideTime,
			startPosition,
			slideLength,
			wheelStep,
			nextTarget,
			destination,
			index = 0,
			cur = 0,
			wheelInt,
			sign = true,
			sign2 = true,
			sign3 = true,
			isIE = $.browser.msie && $.browser.version < 9 ? true : false,
			isIOs = (navigator.platform.indexOf("iPhone") != -1) || (navigator.platform.indexOf("iPod") != -1) || (navigator.platform.indexOf("iPad") != -1) ? true : false;
		
		init = function() {
			if (isIE)
				wheelDiv.css('background', "url('/@/fit/pic-history-wheels-ie.png') 0 0 no-repeat");
		
			if (isIOs) {
				var blocks = sausage.children('div');

				yearRefs.each(function(){
					var index = $(this).index();
					var width = parseInt($(this).attr('rev'));
					
					blocks.eq(index).css('width',width+'px');
				});
				
				//if (document.images) {
					var i1 = new Image();
					i1.src = '/@/fit/bg-history-slide1.jpg';
					var i2 = new Image();
					i2.src = '/@/fit/bg-history-slide2.jpg';
					var i3 = new Image();
					i3.src = '/@/fit/bg-history-slide3.jpg';
					var i4 = new Image();
					i4.src = '/@/fit/bg-history-slide4.jpg';
					var i5 = new Image();
					i5.src = '/@/fit/bg-history-slide5.jpg';
					var i6 = new Image();
					i6.src = '/@/fit/bg-history-slide6.jpg';
					var i7 = new Image();
					i7.src = '/@/fit/bg-history-slide7.jpg';
					var i8 = new Image();
					i8.src = '/@/fit/bg-history-slide8.jpg';
					var i9 = new Image();
					i9.src = '/@/fit/bg-history-slide9.jpg';
				//}
			}

			fitSize();
			
			$(window).bind('resize', function() {
				if (sign)
					fitSize();

				sign = false;
				setTimeout(function(){ sign = true; }, 1000);
			});
			
			yearBtnNumber.eq(0).fadeIn(settings.slideSpeed/16);
			
			yearBtn.draggable({
				axis: 'x', 
				containment: 'parent',
				stop: function() {
					var shift = parseInt($(this).css('left'));
					index = Math.floor(shift/yearBtnStep);
					
					var tail = shift%yearBtnStep;
					
					if (tail > 52)
						index++;
						
					cur = yearRefs.filter('.active').index();
					
					$(this).animate({left: index*yearBtnStep+'px'}, yearBtnSpeed);

					rotateInit();
				}
			});
			
			yearRefs.bind('click', function(e){
				e.preventDefault();
			
				if (!sign3)
					return;
			
				index = $(this).index();
				cur = yearRefs.filter('.active').index();
				
				yearBtn.animate({left: index*yearBtnStep+'px'}, yearBtnSpeed);

				rotateInit();
			});
			
			/*target.touchwipe({
				wipeLeft: function() { sideSlide('right'); },
				wipeRight: function() { sideSlide('left'); }/*,
				preventDefaultEvents: false
			});*/
		}
		
		function sideSlide(direction) {
			if (direction == 'left') {
				cur = yearRefs.filter('.active').index();
				if (cur > 0) {
					index = cur-1;

					yearBtn.animate({left: index*yearBtnStep+'px'}, yearBtnSpeed);

					rotateInit();
				} 
			} else if (direction == 'right') {
				cur = yearRefs.filter('.active').index();
				if (cur < 8) {
					index = cur+1;

					yearBtn.animate({left: index*yearBtnStep+'px'}, yearBtnSpeed);

					rotateInit();
				} 
			}
		}
		
		rotateInit = function() {
			if (index != cur) {
				stepCount = yearRefs.eq(index).attr('name') -  yearRefs.eq(cur).attr('name');

				if ( stepCount > 0 ) {
					direction = 'right';
				} else {
					stepCount = -1*stepCount;
					direction = 'left';
					leftStepCount = 0;
				}
				
				rotate(direction); //Trigger rotation immediately
				
				yearBtnNumber.filter(':visible').fadeOut(settings.slideSpeed);
				yearBtnNumber.eq(index).fadeIn(settings.slideSpeed);
				
				sign3 = false;
				yearBtn.draggable('disable');
			}
		}
		
		rotate = function() { 
			startPosition = parseInt(sausage.css('left'));

			if ( direction == 'right' ) {
				nextTarget = yearRefs.eq(index - stepCount + 1);
			
				wheelPos = 0;
				slideLength = parseInt(nextTarget.attr('rel')) + startPosition;
				destination = -1*nextTarget.attr('rel');
			} else {
				nextTarget = yearRefs.eq(cur - leftStepCount - 1);
				if ( !(isIE && wheelPos > 5) ) {
					wheelPos = 3;
				}
				slideLength = Math.abs(parseInt(nextTarget.attr('rel')) + startPosition);
				destination = -1*nextTarget.attr('rel');
			}
  			
			wheelStep = slideLength/32;
			wheelRotationCounter = 0;
			sign2 = true;
		
			if (!isIOs)
				sausage.css('left', startPosition+'px').animate({ 'left': destination+'px' }, { duration:settings.slideSpeed, easing: 'linear', 
				step: function _stepCallback(now,opts) { 
					newWheelRotationCounter = Math.floor(Math.abs(Math.abs(startPosition)-Math.abs(now))/wheelStep);

					if (wheelRotationCounter != newWheelRotationCounter) {
					wheelRotationCounter = newWheelRotationCounter;
					rotateWheel(direction);
					}
				},
				complete: function _completeCallback() {
					stepCount--;
					leftStepCount++;

					wheelNumber = parseInt(nextTarget.attr('name'))-1;
					
					wheelRotationCounter = 0;
					wheelPos = 1;

					if ( stepCount > 0 )
						rotate(direction);
					else {
							yearRefs.removeClass('active'); //Remove all active class
							yearRefs.eq(index).addClass('active'); //Add active class

						if (!(isIE && (wheelNumber == '3' || wheelNumber == '8'))) {
								setTimeout(function() { wheelDiv.css('backgroundPosition', '0 '+(-1*wheelNumber*wheelSize) + 'px'); }, settings.slideSpeed/32);
						}

						if (isIE) {
							if (wheelNumber == '3' || wheelNumber == '8') {
								wheelShadow.css('display', 'none');
								wheelPos = 8;
							} else {
								wheelShadow.css('display', 'block');
							}
						}

						sign3 = true;
							yearBtn.draggable('enable');
					}
				}
			}); 
			else {
				stepCount--;
				leftStepCount++;

				wheelRotationCounter = 0;
				wheelPos = 1;

				//Slider Animation
				sausage.css({
					'-webkit-transform': 'translate3d('+destination+'px, 0px, 0px)',
					'-webkit-transition': '-webkit-transform '+(settings.slideSpeed/1000)+'s linear' 
				});
				
				wheelInt = setInterval(function() { rotateWheel(direction); }, settings.slideSpeed/32);

				if ( stepCount > 0 ) {
					setTimeout(function() { rotate(direction); clearInterval(wheelInt); }, settings.slideSpeed);
				}
				else {
					setTimeout(function() {
						yearRefs.removeClass('active'); //Remove all active class
						yearRefs.eq(index).addClass('active'); //Add active class 
						
						/*wheelNumber = parseInt(nextTarget.attr('name'))-1;
						wheelDiv.css('backgroundPosition', '0 '+(-1*wheelNumber*wheelSize) + 'px');*/
						
						sign3 = true;
						yearBtn.draggable('enable');
					}, settings.slideSpeed);
				}
			}
		}
		
		function rotateWheel(direction) {
			if (isIOs)
				wheelRotationCounter++;
		
			if ( direction == 'right' ) {
				if (isIE) {
					if (wheelRotationCounter < 16 && !wheelShadow.is(':visible')) {
						wheelShadow.css('display', 'block');
					}
				
					if (wheelPos < 5)
						wheelPos++;

					if (wheelPos == 4) 
						wheelPos = 1;
				
					if (wheelRotationCounter == 16) 
						wheelPos = 5;
					if (wheelRotationCounter == 18) {
						wheelPos = 6;
						wheelShadow.css('display', 'none');
					}
					if (wheelRotationCounter == 20) {
						wheelPos = 7;
						wheelNumber++;
					}
					
					if (wheelNumber != '3' && wheelNumber != '8') {
						if (wheelRotationCounter == 22) {
							wheelPos = 6;
							wheelShadow.css('display', 'block');
						}
						if (wheelRotationCounter == 24)
							wheelPos = 5;
						if (wheelRotationCounter > 24 && wheelPos > 4) 
							wheelPos = 1;
					}
				} else {
					if (!isIOs) {
					if (wheelDiv.add(wheelShadow).css('opacity')=='0' && (wheelRotationCounter < 16)) {
						wheelDiv.add(wheelShadow).animate({opacity: '1'}, settings.slideSpeed/4);
				}

				wheelPos++;

				if ( wheelPos == 4 ) 
					wheelPos = 1;
					
				if ( wheelRotationCounter > 16 && sign2 ) {
					sign2 = false;
				
					if (wheelNumber != '2' && wheelNumber != '7')
							wheelDiv.add(wheelShadow).animate({opacity: '.4'}, settings.slideSpeed/6, function(){
								wheelDiv.add(wheelShadow).animate({opacity: '1'}, settings.slideSpeed/6);
						});
						else {
							wheelDiv.add(wheelShadow).animate({opacity: '0'}, settings.slideSpeed/3);
					}
				}
				
				if ( wheelRotationCounter == 20 ) {
					wheelPos = 1;
					wheelNumber++;
				}
				}
				}
				
				if (!isIOs) {
				if (wheelNumber > 4) 
					wheelTrueNumber = 4;
				else
					wheelTrueNumber = wheelNumber;

				wheelDiv.css('backgroundPosition', (-1*wheelSize*wheelPos) + 'px '+(-1*wheelTrueNumber*wheelSize) + 'px');
				}

				if (isIOs) {
					if (wheelRotationCounter >= 26) {
						clearInterval(wheelInt);
					
						if (stepCount==0) {
							yearRefs.removeClass('active'); //Remove all active class
							yearRefs.eq(index).addClass('active'); //Add active class 
							
							/*wheelNumber = parseInt(nextTarget.attr('name'))-1;
							wheelDiv.css('backgroundPosition', '0 '+(-1*wheelNumber*wheelSize) + 'px');*/
							
							sign3 = true;
							yearBtn.draggable('enable');
						}
					}
				}
			} else {
				if (isIE) {
					if (wheelRotationCounter < 8 && !wheelShadow.is(':visible')) {
						wheelShadow.css('display', 'block');
					}
				
					if (wheelPos < 5)
						wheelPos--;
				
					if ( wheelPos == 0 ) 
						wheelPos = 3;
				
					if (wheelRotationCounter == 8) 
						wheelPos = 5;
					if (wheelRotationCounter == 10) {
						wheelPos = 6;
						wheelShadow.css('display', 'none');
					}
					if (wheelRotationCounter == 12) {
						wheelPos = 7;
						wheelNumber--;
					}
					if (wheelNumber != '3' && wheelNumber != '8') {
						if (wheelRotationCounter == 14) {
							wheelPos = 6;
							wheelShadow.css('display', 'block');
						}
						if (wheelRotationCounter == 16) 
							wheelPos = 5;
						if (wheelRotationCounter > 16 && wheelPos > 4) 
							wheelPos = 1;
					}
			} else {
				wheelPos--;

				if ( wheelPos <= 0 ) 
					wheelPos = 3;

				if ( wheelRotationCounter > 8 && sign2 ) {
					sign2 = false;
				
					if (wheelNumber != '4')
							wheelDiv.add(wheelShadow).animate({opacity: '.4'}, settings.slideSpeed/6, function(){
								wheelDiv.add(wheelShadow).animate({opacity: '1'}, settings.slideSpeed/6);
						});
					else
							wheelDiv.add(wheelShadow).animate({opacity: '0'}, settings.slideSpeed/3);
				}
				
				if ( wheelRotationCounter == 12 ) {
					wheelPos = 1;
					wheelNumber--;
				}
				}

				if (wheelNumber > 4) 
					wheelTrueNumber = 4;
				else
					wheelTrueNumber = wheelNumber;

				wheelDiv.css('backgroundPosition', (-1*wheelSize*wheelPos) + 'px '+(-1*wheelTrueNumber*wheelSize) + 'px');
				
				if (isIOs) {
					if (wheelRotationCounter >= 26) {
						clearInterval(wheelInt);
					
						if (stepCount==0) {
							yearRefs.removeClass('active'); //Remove all active class
							yearRefs.eq(index).addClass('active'); //Add active class 
							
							wheelNumber = parseInt(nextTarget.attr('name'))-1;
							wheelDiv.css('backgroundPosition', '0 '+(-1*wheelNumber*wheelSize) + 'px');
							
							sign3 = true;
							yearBtn.draggable('enable');
						}
					}
				}
			}
		}
		
		function fitSize() {
			var index,
				windowWidth = $(window).width(),
				windowHeight = $(window).height(),
			
				paging = $('.paging'),
				wrap = $('#wrapper-history'),
				yearRef9 = yearRefs.eq(8),
				wrapOffset,
				wheelOffset,
				slidesOffset,
				slide9Offset1,
				slide9Offset2,
				sizeDelimeter;

			if ( windowWidth < 1100 ) {
				wrapOffset = 2;
				wheelOffset = 19;
				slidesOffset = 300;
				slide9Offset1 = 405;
				slide9Offset2 = 405;
				sizeDelimeter = 1050;
			} else if ( windowWidth > 1100 && windowWidth < 1300 ) {
				wrapOffset = 133;
				wheelOffset = 39;
				slidesOffset = 150;
				slide9Offset1 = 270;
				slide9Offset2 = 270;
				sizeDelimeter = 1200;
			} else if ( windowWidth > 1300 && windowWidth < 1500 ) {
				wrapOffset = 211;
				wheelOffset = -1;
				slidesOffset = 110;
				slide9Offset1 = 200;
				slide9Offset2 = 205;
				sizeDelimeter = 1400;
			} else if ( windowWidth > 1500 && windowWidth < 1700 ) {
				wrapOffset = 291;
				wheelOffset = -92;
				slidesOffset = 120;
				slide9Offset1 = 122;
				slide9Offset2 = 125;
				sizeDelimeter = 1600;
				} else {
				wrapOffset = 460;
				wheelOffset = -138;
				slidesOffset = 0;
				slide9Offset1 = -45;
				slide9Offset2 = -45;
				sizeDelimeter = 1700;
				}
				
			index = yearRefs.filter('.active').index();
			wrap.css('marginLeft', wrapOffset+'px');
			wheel.css('marginLeft', wheelOffset+'px');

			yearRefs.each(function(){
				$(this).attr('rel', parseInt($(this).attr('baserel'))+slidesOffset);
				});

			if (index!=8)
				if (isIOs)
					sausage.css({
						'-webkit-transform': 'translate3d('+(-1*yearRefs.filter('.active').attr('baserel')-slidesOffset)+'px, 0px, 0px)',
						'-webkit-transition': '-webkit-transform 0s linear'
				});
				else
					sausage.css('left', -1*yearRefs.filter('.active').attr('baserel')-slidesOffset+'px');
				
			if ( windowWidth > sizeDelimeter ) {
				yearRef9.attr('rel', parseInt(yearRef9.attr('baserel'))+slide9Offset1);
				if (index==8)
					if (isIOs)
						sausage.css({'-webkit-transform': 'translate3d('+(-1*yearRefs.filter('.active').attr('baserel')-slide9Offset1)+'px, 0px, 0px)'});
					else
						sausage.css('left', -1*yearRefs.filter('.active').attr('baserel')-slide9Offset1+'px');
				} else {
				yearRef9.attr('rel', parseInt(yearRef9.attr('baserel'))+slide9Offset2);
				if (index==8)
					if (isIOs)
						sausage.css({'-webkit-transform': 'translate3d('+(-1*yearRefs.filter('.active').attr('baserel')-slide9Offset2)+'px, 0px, 0px)'});
					else
						sausage.css('left', -1*yearRefs.filter('.active').attr('baserel')-slide9Offset2+'px');
			}

			if (windowHeight < 700) {
				paging.css('margin','-20px 0 107px');
			} else if (windowHeight > 700 && windowHeight < 800) {
				paging.css('margin','40px 0 17px');
			} else {
				paging.css('margin','120px 0 -33px');
			}
		}
		
		init();
	};
	
	$.fn.wheelDataSlider = function(options) {
		var settings = {speed: 400};
		$.extend(settings,options);

		var target = $(this),
			refs = $(this).find('div.params-nav a'),
			tables_div = target.find('div.tables');
			tables = tables_div.find('table');
			

		height = tables.eq(0).css('height');

		if (tables.eq(1).length > 0)
		{
			height2 = tables.eq(1).css('height');
			height = height > height2 ? height : height2;
		}

		tables_div.css('height', height);

		if (tables.length == 1)
			tables.eq(0).fadeIn(settings.speed);
		else
			tables_div.find('.table_' + $(this).find('div.params-nav a.active').attr('rel')).fadeIn(settings.speed);

		if (refs.length > 1)
		{
			refs.bind('click', function(e) {
				e.preventDefault();
				
				if ( $(this).hasClass('active') )
					return false;
					
				refs.removeClass('active');
				$(this).addClass('active');
			
				tables.fadeToggle(settings.speed);
				
				return true;
			});
		}
		else
		{
			refs.eq(0).css('cursor', 'default');
			refs.bind('click', function(e) {
				return false;
			});
		}
	};
})(jQuery);

function closeGame() {
	var wrap = $q('#game');
	var bg = $q('#game-bg');
//	var bg = $q('#game div.bg');
	var bar = $q('#game-window');
	
	bg.animate({opacity: '0'}, 350, function() {
		bg.add(wrap).css('display','none');
	});

	bar.animate({opacity: '0'}, 150, function() {
		bar.css('display','none');
	});

	return true;
}

$q(document).ready(function() {
	//$q = jQuery.noConflict();
	
	var wlh = window.location.hash;
	if (wlh.length > 0)
	{
		wlh = wlh.replace('#', '').split(';');
		var type = wlh.length > 1 ? wlh[1] : 'car';
		
		openGame (type);
	}
	
	
	$q("input[title!='']").hint();
	
	if ($q('#homepage-slider-wrap').length) {
		$q('#homepage-slider-wrap').homepageSlider();
		QueryLoader.init();
	}

	if ( $q('#technology').length && $q(window).width() < 1200 ) 
		$q('#wrapper-technonlogy').css('padding','0');

	if ($q('#gmap-dealer').length)
	{
		QueryLoader.init();
		$q('#gmap-dealer').gmapDealer({ searchFieldId: 'gmap-search',  searchFieldBtnId: 'gmap-search-btn', coordinateFieldId: 'cur-place' });
	}
	
	if ($q('#gmap-contact').length) 
		$q('#gmap-contact').gmapContact();
	
	if ($q('#vacancy-list').length)
	{

		$q('#vacancy-list').vacancySlider();

		if ($q('#vacancy-list').length == 1)
			$q('#vacancy-list>li:first div').slideDown(1200);

	}
		
//	if (isiPhone()) { $q('a.play').hide(); }

	var d = new Date();
	var y = d.getFullYear();
	if ($q('#footer_year').html() < y) $q('#footer_year').html(y);


	if ($q('#vacancy form').length)
		$q('#vacancy form').formValidate();
	if ($q('#feedback form').length)
		$q('#feedback form').formValidate();
	
	if ( $q('#catalog-filter').length ) {
		$q('#catalog-body').catalog();
		$q('ul.filters').catalogFilterSlider();
		$q('#catalog-body ul').catalogModelBaloon();
	}
	
	if ( $q('#sizeguide').length ) {
		$q('#sizeguide').sizeguideAnimate();
		$q('#sizeguide-slider').sizeguideSlider();
	}
	
	if ( $q('#history-slider').length ) {
		QueryLoader.init();
		$q('#history-slider').historySlider();
	}

	if ($q('#model').length)
		$q('#model div.left-column').wheelDataSlider();
});

