var gallery,panoram,carousel,fixPNG;

var opacity_prop,addon,onajaxload,onblendstop,onresizestop;
function gi(n,e)
{
	return (e||document).getElementById(n)
}
function gt(t,e)
{
	return (e||document).getElementsByTagName(t)
}
function ne(n)
{
	return document.createElement(n)
}
function gtcn(t,c,e){
	var o=(e||document).getElementsByTagName(t);
	for(var i = 0; i < o.length; i++){
		if( o[i].className.indexOf(c) != -1 )
			return o[i];
	}
	return null;
}
function ae(e,t,f,c)
{
	if( !e )return;
	if(e.addEventListener)
		e.addEventListener(t,f,c)
	else if(e.attachEvent)
		e.attachEvent('on'+t,f)
	else
		e['on'+t]=f
}
function paramstoobject(params){
	var object = {};
	var params = params.split('&');
	for(var i = 0; i < params.length; i++){
		var param = params[i].split('=');
		object[param[0]] = param[1];
	}
	return object;
}
var map,ann,showann,hideann,annleft,lineann,linegoann;
function show_announce(e){
	var vinoski = gi('vinoski');
	if( !e.id || e.id.indexOf('pan') == -1 )
		return false;
	if( vinoski ){
		var o = gt('DIV', vinoski);
		for(var i = 0; i < o.length; i++){
			if( o[i].className.indexOf(e.id) != -1){
				annleft = e.style.left;

				o[i].style.left = e.style.left;
				e.style.visibility = 'hidden';
				showann = o[i];
				linegoann = 1;
			}
			else if( o[i].style.display != 'none' && o[i].className.indexOf('announce') != -1 ){
				var obj = gi(o[i].className.substr(0,o[i].className.indexOf(' ')));
				if( obj ){
					lineann = obj;
				}
				hideann = o[i];
			}
		}
		onblendstop = show_ann;
		fade_announce(hideann,1);
	}
}
function show_ann(){
	var posann = gi('pos');
	posann.style.left = annleft;
	onblendstop = null;
	linegoann = 0;
	fade_announce(showann,false);
}
var wci;
function fade_announce(element,is_hide){
	if( !element ){
		if( onblendstop )
			onblendstop();
		return;
	}
	opacity = (is_hide ? 1 : 0);
	setElementOpacity(element,opacity);
	element.style.display = '';

	var posann = gi('pos');
	if( posann ){
		posann.style.marginTop = Math.round(140*(1-opacity))+'px';
	}
	if( !linegoann && lineann )
		lineann.style.visibility='visible';

	if( wci ){
		window.clearInterval(wci);
	}
	wci = window.setInterval(function()
	{
		opacity += (is_hide ? -0.1 : 0.1);
		if( !is_hide && opacity >= 1 || is_hide && opacity <= 0 )
		{
			if( is_hide ){
				element.style.display='none';
			}
			setElementOpacity(element,1);
			posann.style.marginTop = '0px';
			element.style.marginTop = '0px';
			window.clearInterval(wci);
			if( onblendstop )
				onblendstop();
		}
		else{
			var val = Math.round(70*(1-opacity));
			if( posann )
				posann.style.marginTop = Math.round(140*(1-opacity))+'px';

			element.style.marginTop = val+'px';
			if( !linegoann && lineann )
				setElementOpacity(lineann,opacity);
			setElementOpacity(element,opacity);
		}
	}
	,15);
}

function main()
{
	map = gi('map');
	ann = gi('announc');
	if( map )
		ae(map,'click',show_announce,1);

	if( addon ){
		for(i=0;i<addon.length;i++)
			addon[i]();
	}
}

function blending(id,is_hide){
	var wci,element2,element;
	opacity = is_hide ? 1 : 0;

	if( id[0] == 'two' ){
		element = gi(id[1]);
		element2 = gi(id[2]);
	}
	else
		element = gi(id);

	setElementOpacity(element,opacity);
	if( element2 )
		setElementOpacity(element2,1-opacity);

	element.style.display='';
	if( element2 )
		element2.style.display='';
	wci = window.setInterval(function()
	{
		opacity += is_hide ? -0.1 : 0.1;
		if( !is_hide && opacity >= 1 || is_hide && opacity <= 0 )
		{
			if( is_hide ){
				element.style.display='none';
			}
			if( element2 ){
				element2.style.display='none';
				setElementOpacity(element2,1);
			}
			if( onblendstop )
				onblendstop();
			window.clearInterval(wci);
		}
		else{
			setElementOpacity(element,opacity);
			if( element2 )
				setElementOpacity(element2,1-opacity);
		}
	}
	,5);
}

function getabsposition(element){
	var offsetLeft = 0;
	var offsetTop = 0;
	while(element){
		offsetLeft += element.offsetLeft;
		offsetTop += element.offsetTop;
		element = element.offsetParent;
	}
	if (navigator.userAgent.indexOf("Mac") != -1 && typeof document.body.leftMargin != "undefined") {
		offsetLeft += document.body.leftMargin;
		offsetTop += document.body.topMargin;
	}
	return {left:offsetLeft,top:offsetTop};
}

var opacity_prop;
function setElementOpacity(elem, nOpacity)
{
	if( !opacity_prop )
   		opacity_prop = getOpacityProperty();
  	if(!elem || !opacity_prop)
		return;

	if (opacity_prop=="filter")
	{
		nOpacity *= 100;

		var oAlpha = elem.filters['DXImageTransform.Microsoft.alpha'] || elem.filters.alpha;

		if (oAlpha)
			oAlpha.opacity = nOpacity;
    	else
			elem.style.filter += "progid:DXImageTransform.Microsoft.Alpha(opacity="+nOpacity+")";
  	}
  	else
    	elem.style[opacity_prop] = nOpacity;
}

function getOpacityProperty()
{
  if (typeof document.body.style.opacity == 'string') // CSS3 compliant (Moz 1.7+, Safari 1.2+, Opera 9)
    return 'opacity';
  else if (typeof document.body.style.MozOpacity == 'string') // Mozilla 1.6 и младше, Firefox 0.8
    return 'MozOpacity';
  else if (typeof document.body.style.KhtmlOpacity == 'string') // Konqueror 3.1, Safari 1.1
    return 'KhtmlOpacity';
  else if (document.body.filters && navigator.appVersion.match(/MSIE ([\d.]+);/)[1]>=5.5) // Internet Exploder 5.5+
    return 'filter';
  return false;
}

var my = {
	lock:0,
	
	onready: new Array(),
	onload: new Array(),
	
	panorams:new Array(),
	carousels:new Array(),
	galleries:new Array(),
	connector: ((new Date()).getTime()),
	/*
	 *  Возвращает абсолютные координаты элемента на странице
	 */
	getXY:function(element)
	{
		var x = 0;
		var y = 0;
		while(element)
		{
			x += element.offsetLeft;
			y += element.offsetTop;
			element = element.offsetParent;
		}
		if(navigator.userAgent.indexOf("Mac") != -1 && typeof document.body.leftMargin != "undefined")
		{
			x += document.body.leftMargin;
			y += document.body.topMargin;
		}
		return {x:x,y:y}
	},
	
	hide:function(){
		if( panoram )
			panoram.hide();
		
		if( carousel )
			carousel.hide();
		
		if( gallery )
			gallery.hide();
	},
	
	/*
 	 *  Класс для создания плейсхолдера
 	 */
	placeholder: {
		nativePlaceholder:(navigator.userAgent.match(/Safari/)),
	
		blurevent:function()
		{
			if(!this.value || this.value == '' || this.value == this.title)
			{
				this.value = this.title;
				$(this).removeClass('placetext');
			}
		},
	
		focusevent:function()
		{
			if(this.value == this.title)
				this.value = '';
			$(this).addClass('placetext');
		},
	
		init:function(){
			var input = $(this);
			if(my.placeholder.nativePlaceholder)
			{
				input.placeholder = input.title;
			}
			else
			{
				input.focus(my.placeholder.focusevent).blur(my.placeholder.blurevent);	
				input.blur();
			}
		}
	},

	
	/*
 	 *  Класс проигрывает мультик из кадров для объекта image
 	 */
	movie:function(image)
	{
			image.css('width',image.width());
			image.css('height',image.height());
			image[0].src = '/i/0.gif';
			image.css('background','url(/i/mixermovie.gif) 0 -297px no-repeat')
			image[0].play = function(){
				if( image[0].frame < 11 )
					image[0].frame += 1;
				else
					image[0].frame = 0;
				image[0].style.backgroundPosition = '0 -'+(297 - image[0].frame * 27)+'px';
				if( !image[0].stopped )
					setTimeout(image[0].play,50);
			};
			image[0].frame = 0;
			image.mouseover(function()
			{
				this.stopped = 0;
				setTimeout(this.play,100);
			});
			image.mouseout(function()
			{
				this.stopped = 1;
			});
	},
	
	/*
	 *  Функция выполняющаяся после загрузки всей страницы
	 */
	load:function()
	{
		// Добавляем вызов функций на наведение мыши для машинок
		$('#flashcars').mouseover(function()
		{
			var obj = swfobject.getObjectById("flashcars");
			if (obj && typeof obj.mouseOver != "undefined" )
				obj.mouseOver();
			}).mouseout(function(){
			var obj = swfobject.getObjectById("flashcars");
			if (obj && typeof obj.mouseOut != "undefined" )
				obj.mouseOut();
		});
		
		// Добавляем мультик для бетономешалки
		var mixer = $('#mixer');
		if( mixer.size() )
			my.movie(mixer);
		
		for(var i = 0; i < my.onload.length; i++)
			my.onload[i]();
		
		//bottom:0 bug fix
		document.body.className+='';
	},
	
	/*
	 *  Основня функция, когда DOM готов для модификации
	 */
	ready:function()
	{
		$('input.placeholder').each(my.placeholder.init);	
		main();
		
		for(var i = 0; i < my.onready.length; i++)
			my.onready[i]();
	},
	
	/*
 	 *  Добавляем навигацию с клавиатуры
 	 */
	keynavigation:function(e){
		if(e.ctrlKey)
		{
			var link = null;
			var href = null;
			switch (e.keyCode ? e.keyCode : e.which ? e.which : null)
			{
				case 0x25:
					link = $('#prevLink');
					break;
				case 0x27:
					link = $('#nextLink');
					break;
        	    case 0x26:
					link = $('#upLink');
					break;
				case 0x28:
					link = $('#downLink');
					break;
				case 0x24:
					link = $('#homeLink');
					break;
			}
			if (link && link[0]) document.location = link[0].href;
			if (href) document.location = href;
		}
	},
	
	/*
	 *  Создает объект анимирующий вылетание изображения
	 */
	resizer:function(from, to, image, frames){
		var animation = {
			//Изображение, которое мы перемещаем
			image:0,
			//Позиция с которой перемещаем
			from:0,
			//Позиция в которую перемещаем
			to:0,
			//Текущая позиция в анимации
			step:0,
			
			init:function(picture){
				animation.image = document.createElement('IMG');
				animation.image.src = picture;
				animation.image.style.position = 'absolute';
				animation.image.style.left = '-1000%';
				animation.image.style.zIndex = 10000;
				document.body.appendChild(animation.image);
			},
			
			position:function(from, to){
				animation.from = my.getXY(from);
				animation.from.width = from.clientWidth;
				animation.from.height = from.clientHeight;
				animation.from.object = from;
				
				to.style.visibility = 'hidden';
				to.style.display = '';
				animation.to = my.getXY(to);
				animation.to.width = to.clientWidth;
				animation.to.height = to.clientHeight;
				animation.to.object = to;
				to.style.display = 'none';
				to.style.visibility = 'visible';
			},
			
			show:function(from, to, params){
				animation.position(from, to);
				if( params )
				{
					if( params.towidth )
						animation.to.width = params.towidth;
				
					if( params.towidth )
						animation.to.height = params.toheight;
				}
				animation.image.width = animation.from.width;
				animation.image.height = animation.from.height;
				animation.image.style.top = animation.from.y;
				animation.image.style.left = animation.from.x;
				
							
				animation.side = 0;
				animation.step = 1;
				animation.animation();
			},
			
			hide:function(from, to){
				if( from )
					animation.from.object = from;
				if( to )
					animation.to.object = to;
				animation.image.width = animation.to.width;
				animation.image.height = animation.to.height;
				animation.image.style.top = animation.to.y;
				animation.image.style.left = animation.to.x;
				animation.to.object.style.display = 'none';
				
				animation.side = 1;
				animation.step = 0;
				animation.animation();
			},
			
			animation:function(){
				if( animation.side )
					animation.step += 0.08;
				else
					animation.step -= 0.08;

				if( animation.side && animation.step >= 1 || !animation.side && animation.step <= 0 )
				{
					if( animation.side )
						animation.step = 1;
					else
						animation.step = 0;

					if( animation.onstop )
						animation.onstop();
				}
				animation.image.style.left = Math.round(animation.from.x * animation.step + (1 - animation.step) * animation.to.x)+ 'px';
				animation.image.style.top = Math.round(animation.from.y * animation.step + (1 - animation.step) * animation.to.y) + 'px';
				animation.image.width = Math.round(animation.step * animation.from.width + (1 - animation.step) * animation.to.width);
				animation.image.height = Math.round(animation.step * animation.from.height + (1 - animation.step) * animation.to.height);

				if( animation.step != 1 && animation.step != 0 )
					setTimeout(animation.animation,21);
				else
				{
					if( !animation.side )
						animation.to.object.style.display = '';
					animation.image.style.left = '-1000%';
				}
			}
		};
		
		animation.init(from, to, image, frames);
		
		return animation;
	}
};
/*
var test = {
	
	test_mode:0,
	
	init:function()
	{
		test.element = document.createElement('DIV');
		test.element.style.position = 'absolute';
		test.element.style.top = '0';
		test.element.style.right = '0';
		test.element.style.zIndex = '10000000';
		test.element.style.background = '#fff';
		test.element.style.border = '1px solid red';
		test.element.style.overflow = 'auto';
		test.element.style.width = '200px';
		test.element.style.height = '200px';
		test.element.innerHTML = '';
		if( new String(document.location).indexOf('design.ru') != -1 )
		{
			test.test_mode = 1;
			document.body.appendChild(test.element);
		}
	},
	
	out:function(msg)
	{
		test.element.innerHTML += msg + '<br />';
	}
};
my.onready.push(test.init);
*/
$(window).load(my.load);
$(document).ready(my.ready).keydown(my.keynavigation);