function CustomAnimation(callback, duration, swing, comlete) {
	if ((typeof duration != 'number') || (typeof callback != 'function') || (typeof swing != 'boolean')) {
		return false;
	}
	var _startTime = (new Date()).getTime();

	var _Timer = setInterval(function(){
		var _inWork = (new Date()).getTime() - _startTime;
		var X = _inWork / duration;
		X = X > 1 ? 1 : X;
		if (swing) {
			X = ((-Math.cos(X*Math.PI)/2) + 0.5);
		}
		callback(X);
		if (_inWork >= duration) {
			clearInterval(_Timer);
			if (typeof comlete == 'function') {
				comlete();
			}
		}
	}, 1);
	return _Timer;
}

function InstallJSFix() {
	$('#menumenu li:last').addClass('last');
}

function InstallIEFix() {
	if ($.browser.msie) {
		$('#index .switch-video, \
		#second-slideshow .arrows, \
		#second-slideshow .turning, \
		#second-rotated-screens .text, \
		#second-rotated-screens .closebg').each(function(){
			fixPNG(this);
		});
		$('img.png').each(function(){
			fixPNG(this);
		});
		
		$('#menumenu li').hover(function(){
			$(this).addClass('hover').find('div').addClass('hover');
		}, function(){
			$(this).removeClass('hover').find('div').removeClass('hover');
		});
		
		$('table.decor tr').hover(function(){
			$(this).addClass('hover');
		}, function(){
			$(this).removeClass('hover');
		});
		
		$('#second .contacts').css('bottom', -1);
	}
}

function InstallSecondSlideshow(images) {
	var slideshow = $('#second-slideshow');
	var thisImg = slideshow.find('img:first');
	var current = 0;
	
	images.unshift({img: thisImg.attr('src'), name: slideshow.find('.arrows span').text()});
	
	function updateFrame(left) {
		current += left ? -1 : 1;
		if (current < 0) {
			current += images.length;
		}
		var image = new Image();
		image.src = images[current % images.length].img;
		var timer = setInterval(function(){
			if (image.complete) {
				clearInterval(timer);
				slideshow.prepend(image);
				var newImg = $(image).addClass('moved')
					.css({left: left ? 960 : -960})
					.animate({left: 0}, 500, function() {
						thisImg.remove();
						thisImg = newImg.removeClass('moved');
					});
				slideshow.find('div.arrows span').text(images[current % images.length].name);
			}
		}, 50);
	}
	slideshow.find('a.left').click(function(){
		updateFrame(true);
		return false;
	});
	slideshow.find('a.right').click(function(){
		updateFrame(false);
		return false;
	});
	slideshow.find('.turning').click(function() {
		$('#second-rotated-screens').show();
		slideshow.hide();
	});
	$('#second-rotated-screens .close').click(function(){
		$('#second-rotated-screens').hide();
		slideshow.show();
		return false;
	});
}

var PictureSlider_timer = false;
var PictureSlider_images = false;
var PictureSlider_parts = false;
var PictureSlider_current = false;
function InstallPictureSlider(images) {

	var pictureSlider = $('#screen-default');
	var current = 1;
	var partsCount = 3;
	var parts = [];
	
	if (typeof images == 'boolean') {
		if ( ! images) {
			/*$('#screen-default .part').remove();*/
			clearInterval(PictureSlider_timer);
			PictureSlider_timer = false;
			return;
		} else {
			images = PictureSlider_images;
			parts = PictureSlider_parts;
			current = PictureSlider_current;
		}
	} else {
		images.unshift(pictureSlider.find('img').attr('src'));
		for (var i = 0; i < partsCount; i++) {
			parts.push($('<div class="part"></div>').appendTo(pictureSlider));
		}
		
		PictureSlider_parts = parts;
		PictureSlider_images = images;
	}

	PictureSlider_timer = setInterval(function(){
		var cacheImage = new Image();
		cacheImage.src = images[current % images.length];
		var cacheTimer = setInterval(function(){
			if (cacheImage.complete) {
				clearInterval(cacheTimer);
				
				for (var i = 0; i < partsCount; i++) {
					parts[i].css({
						display: 'block',
						width: '0',
						backgroundImage: 'url(' + cacheImage.src + ')',
						left: ((960 / partsCount) * i).toString() + 'px'
					});
				}
				CustomAnimation(function(x){
					var width = (960 / partsCount) * x;
					for (var i = 0; i < partsCount; i++) {
						parts[i].css({
							width: width,
							backgroundPosition: (-(960 / partsCount)*i).toString() + 'px 0'
						});
					}
				}, 500, true, function(){
					pictureSlider.find('img:first').attr('src', cacheImage.src);
					pictureSlider.find('.part').hide();
					current++;
					PictureSlider_current = current;
				});
			}
		}, 100);
	}, 5000);
}

function InstallRotatedScreen(el) {
	var wind = el.find('.window');
	el.show();
	var windwidth = wind.width() + 2;
	el.hide();
	var elget = el.get(0);
	var img = wind.find('img');
	var currenFrame = 0;
	var needFrame = 0;
	var pageX = 0;
	
	var imgtimer = setInterval(function(){
		if (img.get(0).complete) {
			clearInterval(imgtimer);
			
			setInterval(function() {
				if (elget.offsetWidth) {
					var x = Math.max(0, Math.min(0.99, (pageX - el.offset().left) / elget.offsetWidth));
					var frames = img.width() / windwidth;
					needFrame = Math.floor(x * frames);
					
					if (needFrame != currenFrame) {
						currenFrame += currenFrame < needFrame ? 1 : -1;
						img.css({left: -windwidth*currenFrame});
					}
				}
			}, 20);
			
			$('body').mousemove(function(e){
				pageX = e.pageX;
			});
		}
	}, 50);
}

function InstallIndex() {
	var partsItems = $('#parts .item');

	function StartInteractive(item){
		var screens = $('#screen .screen').each(function(){
			if (this.style.zIndex != 15) {
				this.style.display = 'none';
			}
			this.style.zIndex = 12;
		});
		switch (item) {
			case 1:
				InstallPictureSlider(false);
				$('#screen-company').hide().fadeIn(300).css({zIndex: 15});
				break;
			case 2:
				InstallPictureSlider(false);
				$('#screen-production').hide().fadeIn(300).css({zIndex: 15});
				break;
			case 3:
				InstallPictureSlider(false);
				$('#screen-benefits').hide().fadeIn(300).css({zIndex: 15});
				break;
			default:
				var slogo = $('#screen-default .slogo').show();
				InstallPictureSlider(true);
				screens.fadeOut(300, function(){
					slogo.show().fadeIn(500);
				});
		}
	}


	var animationTimer = false;
	function Select(item, lastItem) {
		if (animationTimer) {
			clearInterval(animationTimer);
			animationTimer = false;
		}
		partsItems.not('#parts .p' + lastItem)
			.css({margin: '0 0 -50px'})
			.find('.inside')
			.css({
				paddingTop: '18px',
				height: '192px',
				backgroundColor: 'white'
			})
			.end()
			.find('.hidden')
			.css({
				display: 'block',
				height: 0
			});
			
		StartInteractive(item);
		
		var direction;
		if (item) {
			item = $(partsItems[item-1]);
			direction = true;
		} else {
			item = $(partsItems[lastItem-1]);
			direction = false;
		}
		
		var inside = item.find('.inside');
		var hidden = item.find('.hidden');
		
		animationTimer = CustomAnimation(function(x){
			if ( ! direction) {
				x = 1-x;
			}
			var itemMargin = Math.round(-246*x);
			var insidePadding = Math.round((38-18)*x);
			var insideHeight = Math.round((200-192)*x);
			var hiddenHeight = - itemMargin - insidePadding;
			var bg = (0xFF + Math.round((0xE6 - 0xFF)*x)).toString();
			
			item.css({
				marginTop: itemMargin.toString() + 'px'
			});
			inside.css({
				paddingTop: (18 + insidePadding).toString() + 'px',
				height: (192 + insideHeight).toString() + 'px',
				backgroundColor: 'rgb(' + bg + ',' + bg + ',' + bg + ')'
			});
			hidden.css({
				height: hiddenHeight.toString() + 'px'
			});
		}, 300, false, function(){
			animationTimer = false;
		});
	}

	var partsTimer = false;
	var lastSelectItem = 0;
	partsItems.hover(function(){
		if (partsTimer) {
			clearTimeout(partsTimer);
			partsTimer = false;
		}
		if (lastSelectItem != this.__i) {
			Select(this.__i);
			lastSelectItem = this.__i;
		}
	}, function(){
		if (partsTimer) {
			clearTimeout(partsTimer);
			partsTimer = false;
		}
		partsTimer = setTimeout(function(){
			partsTimer = false;
			Select(0, lastSelectItem);
			lastSelectItem = 0;
		}, 300);
	}).each(function(i){
		this.__i = i+1;
	}).removeClass('hovered');

	var productionTimer =false;
	$('#production-list li a').hover(function(){
		if (productionTimer) {
			clearTimeout(productionTimer);
			productionTimer = false;
		}
		$('#parts .p2 .headline .pic').attr('src', this.rel);
	}, function(){
		if (productionTimer) {
			clearTimeout(productionTimer);
			productionTimer = false;
		}
		productionTimer = setTimeout(function(){
			productionTimer = false;
			$('#parts .p2 .headline .pic').attr('src', '/iart/1x1.gif');
		}, 100);
	}).each(function(){
		$(new Image()).attr('src', this.rel);
	});
	
	if ($.fn.flash.hasFlash()) {
		var embedded = false;
		$('#index .switch-video').addClass('on').click(function(){
		
			$('#parts, #screen-default').hide();
			//$('#screen-video-player').css({visibility: 'visible'});
			$('#screen-video-player').css({height: 600});
			InstallPictureSlider(false);
			
			var interval = setInterval(function() {
				try {
					uppodSend('screen-video-player', 'play');
					uppodSend('screen-video-player', 'getstatus');
					uppodSend('screen-video-player', 'text:Нажмите Стоп для возврата');
					clearInterval(interval);
				} catch (e) {
				}
			}, 10);
			
			if ( ! embedded) {
				new swfobject.embedSWF('/swf/uppod.swf', 'screen-video-player', 960, 600, '9.0.0', false, {
						uid: 'screen-video-player',
						st: 'vcyckHJz3iuLkCJa2xo401nWvQEzyHmb6iTr',
						file: 'va4h3ITL0xwZ2xEL2xmb35sVtSm50iUr'
						//file: 'va4h3ITL0xwZ2xEL2xmZkfDBk5Wa'
					}, {
						bgcolor: '#ffffff',
						allowFullScreen: 'true',
						allowScriptAccess: 'always',
						wmode: 'window'
					}, {
						id: 'screen-video-player'
					});
				$('#screen-video-player').show();
				embedded = true;
			}
		});
	}
}
function uppodCancelVideo() {
	$('#parts, #screen-default').show();
	/* I use this becouse of fucken IE */
	$('#screen-video-player').css({height: 0});
	InstallPictureSlider(true);
	uppodSend('screen-video-player', 'pause');
}

function uppodGetStatus(status) {
	if (status == 0) {
		uppodCancelVideo();
	}
}

function InstallFloats() {
	$('#login-link').click(function() {
		var form = $('#login-form');
		if (form.is(':visible')) {
			form.trigger('floathide').hide();
		} else {
			form.trigger('floatshow').show();
		}
		return false;
	});
	$('#login-form').bind('floathide', function() {
		$('#login-link').removeClass('pressed');
	}).bind('floatshow', function() {
		$('#login-link').addClass('pressed');
	});

	$('#request-link').click(function() {
		var form = $('#request-form');
		if (form.is(':visible')) {
			form.trigger('floathide').hide();
		} else {
			form.trigger('floatshow').show();
		}
		return false;
	});
	
	$('#request-form').bind('floathide', function() {
		$(this).find('.warnTextThere')
			.removeClass('warnText')
			.html('')
			.end()
			.find(':submit')
			.removeAttr('disabled');
		$('#request-link').removeClass('pressed');
	}).bind('floatshow', function() {
		$('#request-link').addClass('pressed');
	}).find('form').submit(function(){
		$(this).find(':submit').attr('disabled', 'disabled');
		$(this).append("<input type='hidden' name='requested-with' value='ajax' />");
		$(this).ajaxSubmit({
				success: function(response){
					if (response) {
						$('#request-form').find('.warnTextThere')
							.addClass('warnText')
							.html(response)
							.end()
							.find(':submit')
							.removeAttr('disabled');
					} else {
						alert('Запрос отправлен. С вами свяжутся.');
						$('#request-form').trigger('floathide').hide();
					}
				},
				error: function() {
					$('#request-form').find('.warnTextThere')
						.addClass('warnText')
						.html(response)
						.end()
						.find(':submit')
						.removeAttr('disabled');
					alert('Не удалось отправить данные');
				}
			});
		return false;
		
	});
	$('.make_order').click(function() {
		var form = $(this).parent().find('.request-form');
		
		if (form.is(':visible')) {
			form.trigger('floathide').hide();
		} else {
			form.trigger('floatshow').show();
		}
		return false;
	});

	$('.request-form').bind('floathide', function() {
		$(this).find('.warnTextThere')
			.removeClass('warnText')
			.html('')
			.end()
			.find(':submit')
			.removeAttr('disabled');
	}).bind('floatshow', function() {
	}).find('form').submit(function(){
		
		requestform = $(this).parent().parent();
		
		$(this).find(':submit').attr('disabled', 'disabled');
		$(this).append("<input type='hidden' name='requested-with' value='ajax' />");
		$(this).ajaxSubmit({
				success: function(response){
					if (response) {
						requestformfind('.warnTextThere')
							.addClass('warnText')
							.html(response)
							.end()
							.find(':submit')
							.removeAttr('disabled');
					} else {
						alert('Запрос отправлен. С вами свяжутся.');
						requestform.trigger('floathide').hide();
					}
				},
				error: function() {
					requestform.find('.warnTextThere')
						.addClass('warnText')
						.html(response)
						.end()
						.find(':submit')
						.removeAttr('disabled');
					alert('Не удалось отправить данные');
				}
			});
		return false;
		
	});

	
	
	
	function InstallLeaveOrder() {
		var form = $('#leave-order-form form').append("<input type='hidden' name='is_ajax' value='1' />");
		form.find(':text').keypress(function(e){
			window.status = e.which;
			if (e.which == 27) {
				$('#leave-order-form').trigger('floathide').hide();
				return true;
			}
			if ((e.which == 13) || (e.which == 46) || (e.which == 35) || (e.which == 36) || (e.which == 8)) {
				return true;
			}
			if ((e.which >= 37) && (e.which <= 40)) {
				return true;
			}
			return e.ctrlKey || (e.which >= 48) && (e.which <= 57);
		}).focus();
		form.ajaxForm({
				url: form.attr('ajax'),
				target: '#leave-order-form .content',
				success: function(){
					InstallLeaveOrder();
				},
				error: function() {
				}
			});
	}
	InstallLeaveOrder();
	
	$('#leave-order-link').click(function() {
		var form = $('#leave-order-form');
		if (form.is(':visible')) {
			form.trigger('floathide').hide();
		} else {
			form.trigger('floatshow').show();
		}
		return false;
	});
	$('#leave-order-form').bind('floathide', function() {
		$('#leave-order-link').removeClass('pressed');
	}).bind('floatshow', function() {
		$('#leave-order-link').addClass('pressed');
	});
	
	$('div.float .close').click(function() {
		$(this).parents('div.float')
			.trigger('floathide')
			.hide();
		return false;
	});
}

function InstallFuncyBoxes() {
	$('a[rel=lightbox], \
	a[rel=lightbox-attach]')
	.fancybox({
		zoomSpeedChange: 0,
		zoomSpeedIn: 0,
		zoomSpeedOut: 0,
		overlayOpacity: 0.2,
		padding: 30
	});
}

function InstallSlider() {
	$(".article_slider").find(".article_header").bind("click", function(){
		$(".article_text").hide();
		
		var id = $(this).attr('text_id');
		$(".article_text[text_id='"+ id +"']").show();
		
		return false;
	});
}

function InstallYandex() {
	if ( ! $("#contacts_yandex_map").length) {
		return;
	}
	
	var map = new YMaps.Map($("#contacts_yandex_map")[0]);
    map.setCenter(new YMaps.GeoPoint(37.515066,55.870516), 13, YMaps.MapType.MAP);
	map.addControl(new YMaps.Zoom());
	map.addControl(new YMaps.ToolBar());
	map.addControl(new YMaps.TypeControl());
	map.enableScrollZoom();
	
	var content = document.createElement('span');
    content.innerHTML =('<span>ООО АТВ Алексарт</span><br><span>125635, г.Москва,<br>ул.Талдомская, д.2Г,<br>офис 113</span><br><span>+7(499) 905-27-09</span><br><span>+7(499) 905-27-81</span><br><span>+7(499) 905-30-45</span>');

    map.openBalloon(new YMaps.GeoPoint(37.515066, 55.870516), content);

    var router = new YMaps.Router([
    	'Москва, улица Зеленоградская, 18а',
        'Москва, улица Зеленоградская, 4',
        'Москва, метро Водный стадион'], [1], {viewAutoApply: 0});

    YMaps.Events.observe(router, router.Events.Success, function() {
    	router.getWayPoint(1).setIconContent('Маршрутка 65<br>Автобус 65');
        router.getWayPoint(0).setIconContent('Маршрутка 65');
        map.addOverlay(router);
   	});

	var router1 = new YMaps.Router([
		'Москва, улица Зеленоградская, 18а',
		'Москва, улица Фестивальная, 11с1'], [1], {viewAutoApply: 0});

	YMaps.Events.observe(router, router.Events.Success, function() {
		router1.getWayPoint(1).setIconContent('Маршрутка 89');
		router1.getWayPoint(0).setIconContent('Маршрутка 65<br>Автобус 65<br>Автобус 89');
		map.addOverlay(router1);
    });

	var router2 = new YMaps.Router([
    	'Москва, улица Ангарская, 2к2',
        'Москва, Серпуховско-Тимирязевская линия, метро Петровско-Разумовская'], [1], {viewAutoApply: 0});

    YMaps.Events.observe(router, router.Events.Success, function() {
    	router2.getWayPoint(1).setIconContent('Маршрутка 191');
        router2.getWayPoint(0).setIconContent('Маршрутка 191');
        map.addOverlay(router2);
    });
}

function InstallGoogle() {
	if ( ! $("#contacts_google_map").length) {
		return;
	}
	
	if (GBrowserIsCompatible()) {
		var map = new GMap2(document.getElementById('contacts_google_map'));
		map.setCenter(new GLatLng(55.871925,37.520568), 13);
		map.setMapType(G_NORMAL_MAP);
		map.addControl(new GLargeMapControl());
		map.addControl(new GScaleControl());
		map.addControl(new GMapTypeControl());

		var HelpWin_point = new GLatLng(55.871925,37.520568);
		var HelpWin = new GMarker(HelpWin_point, {title: 'Aleksart'});
		var HelpContent = "<span><span>ALEXART Group of Companies</span><br><span>Taldomskaya Str, 2G, off.113<br>125636, Moscow, Russia</span><br><span>+7 499 905-27-09</span><br><span>+7 499 905-27-81</span><br><span>+7 499 905-30-45</span></span><br><br><br>&nbsp;";
		HelpWin.bindInfoWindowHtml(HelpContent);
		map.addOverlay(HelpWin);
		HelpWin.openInfoWindowHtml(HelpContent);
	}
}

function InstallTabcontrols() {
	$('div.tabcontrol').each(function(){
		var control = $(this);
		var pages = control.find('.pages .tc_item');
		var tabs = control.find('.tc_tabs a').click(function(){
			var $this = $(this);
			if ( ! $this.parent().hasClass('current')) {
				tabs.removeClass('current');
				pages.removeClass('current');
				pages.filter('.' + $this.attr('rel')).addClass('current');
				$this.parent().addClass('current');
			}
			return false;
		}).parent();
	});
	if (window.location.hash) {
		var hash = window.location.hash.substr(1);
		$('div.tabcontrol .tc_tabs a[rel="' + hash + '"]').triggerHandler('click');
		window.location = window.location;
	}
}

$(function(){
	InstallJSFix();
	InstallIEFix();
	InstallIndex();
	InstallFloats();
	InstallFuncyBoxes();
	InstallSlider();
	InstallYandex();
	InstallGoogle();
	InstallTabcontrols();
});
