var cmd;
var onsitetimer = undefined;
var CALLTIME = 25; // в секундах

$(document).ready(function() {
	var browser_msie = new String($.browser.msie + " " + jQuery.browser.version);
/*
	$('body').mouseenter(function() { if(onsitetimer == undefined) onsitetimer = setInterval(onsite, 1000);} )
			 .mouseleave(function()  {clearInterval(onsitetimer); onsitetimer = undefined;} );
*/

	window.onfocus = function() { if(onsitetimer == undefined) onsitetimer = setInterval(onsite, 1000); } 
	window.onblur = function()  {clearInterval(onsitetimer); onsitetimer = undefined;} 
	
	$('a.tooltip').tooltip({
		track: true,
		delay: 0,
		showURL: false,
		fade: 200
	});

	/* MAIN PAGE - CHANGE PEOPLE SIZES & BALOONS */
	$('.main .people li a').mouseenter(function() {
						var className = $(this).parent().attr('class');
						$('.people_baloons li').each(function() {
							$(this).removeClass('active');
							if($(this).hasClass(className)) $(this).addClass('active');
						});
						$(this).find('img').stop().animate({'width': '100%', 'margin-top': '0'}, 100);
						var cur_people = 1 + $('.people_baloons li').index($(".people_baloons").find('li.active'));
						$('ul.menu li:nth-child('+cur_people+')').addClass('active');
						})
					.mouseleave(function() {
						$(this).find('img').stop().animate({'width': '90%', 'margin-top': '20px'}, 100);
						$('ul.menu li').removeClass('active');
					});
					
	$('ul.menu li a').mouseenter(function() {
						var cur_people = 1 + $('ul.menu li a').index($("ul.menu li a:hover"));
						//alert(cur_people);
						$('.people_baloons li').removeClass('active');
						$('.people_baloons li:nth-child('+cur_people+')').addClass('active');
						$('.people li:nth-child('+cur_people+')').find('img').stop().animate({'width': '100%', 'margin-top': '0'}, 100);
						})
					.mouseleave(function() {
						//var cur_people = 1 + $('ul.menu li a').index($("ul.menu li a:hover"));
						$('.people li').find('img').stop().animate({'width': '90%', 'margin-top': '20px'}, 100);
					});
	
	/* HOVERED & CLICKED */
	$('.phone_pad').mouseover(function() {$(this).addClass('hover')})
					.mouseout(function() {$(this).removeClass('hover')});
	
	$('.tabs_block span.f_field').mouseover(function() {$(this).addClass('hover')})
					.mouseout(function() {$(this).removeClass('hover')});

	$('.tabs_block span.f_text').mouseover(function() {$(this).addClass('hover')})
					.mouseout(function() {$(this).removeClass('hover')});

	$('.tabs_block select.styled').mouseover(function() {$(this).parent().find('.select').addClass('hover')})
					.mouseout(function() {$(this).parent().find('.select').removeClass('hover')});

	$('.phone_pad .submit').mousedown(function() {$(this).parent().addClass('clicked')})
					.mouseup(function() {$(this).parent().removeClass('clicked')})
					.mouseout(function() {$(this).parent().removeClass('clicked')});

	$('.button a').mousedown(function() {$(this).addClass('clicked')})
					.mouseup(function() {$(this).removeClass('clicked')})
					.mouseout(function() {$(this).removeClass('clicked')});

	/* INNER PAGES - PEOPLE & BALOON POSITION ABOVE MENU */
	if($("ul.menu").length) {
		var cur_people_baloon = 1 + $("ul.menu li").index($("ul.menu").find('li.active'));
		if($("ul.people_baloons").length) $("ul.people_baloons").addClass("extra_" + cur_people_baloon);
		if($("ul.people").length) $("ul.people").addClass("extra_" + cur_people_baloon);
	}


	var ulWidth;
	/* SIMPLE CAROUSEL */
	if($('.j_carousel.simple').length) $('.j_carousel.simple').jcarousel({
        scroll:	1,
		wrap:	'circular'
    });
	/* STEREO CAROUSEL */
	if($('.j_carousel.stereo').length) $('.j_carousel.stereo').jcarousel({
        scroll:	1,
		wrap:	'circular',
		itemFirstInCallback: function(carousel, item, idx, state) {
			if(carousel.container.hasClass('stereo')) {
				$('.j_carousel.stereo').find('.jcarousel-item').each(function() {
					if($(this).hasClass('active')) {
						$(this).find('img').attr('src', $(this).find('img').attr('rel'));
						$(this).removeClass('active');
					}
				});
				$('.j_carousel.stereo').find('.jcarousel-item-' + (idx + 1)).each(function() {
					$(this).find('img').attr('src', $(this).find('img').attr('alt'));
					$(this).addClass('active');
					$("#girlname").text($(this).find('img').attr('title'));
				});
			}
		},
		setupCallback: function() {
			$('.j_carousel.stereo').parents('.jcarousel-container').addClass('stereo');
			$('.j_carousel.stereo').find('.jcarousel-item-2').each(function() {
				$(this).find('img').attr('src', $(this).find('img').attr('alt'));
				$(this).addClass('active');
				$("#girlname").text($(this).find('img').attr('title'));
			});
		}
    });
	/* AWARDS CAROUSEL */
	if($('.j_carousel.awards').length) $('.j_carousel.awards').jcarousel({
        scroll:	browser_msie == 'true 6.0' ? 1 : 3,
		wrap:	null,
		setupCallback: function() {
			$('.j_carousel.awards').parents('.jcarousel-container').addClass('awards');
			$('.j_carousel.awards').parent().addClass('awards');
			if(browser_msie == 'true 6.0') {
			ulWidth = ($('.j_carousel.awards li').length * 100) + 'px !important';
			}
			else {
			ulWidth = 0;
			$('.j_carousel.awards').find('li').each(function(i, element) {
				var newWidth = $(element).find('img').width();
				$(element).css('width', newWidth + 'px');
				ulWidth += $(element).outerWidth(true);
				});
			}
			$('.j_carousel.awards').css('width', ulWidth + 'px');
		}
    });
	/* GOODS CAROUSEL */
	if($('.j_carousel.goods').length) $('.j_carousel.goods').jcarousel({
        scroll:	1,
		wrap:	'circular',
		setupCallback: function() {
			$('.j_carousel.goods').parents('.jcarousel-container').addClass('goods');
			$('.j_carousel.awards').parent().addClass('goods');
			if(browser_msie == 'true 6.0') {
			ulWidth = ($('.j_carousel.awards li').length * 220) + 'px !important';
			}
			else {
			ulWidth = 0;
			$('.j_carousel.goods').find('li').each(function(i, element) {
				var newWidth = $(element).find('img').width();
				if(newWidth) $(element).css('width', newWidth + 'px');
				ulWidth += $(element).outerWidth(true);
				});
			}
			$('.j_carousel.goods').css('width', ulWidth);
		}
    });
	
	if(browser_msie == 'true 6.0') {
		$('.jcarousel-item-horizontal a').mouseenter(function() {
			$(this).parents('ul').find('span.active').hide();
			$(this).find('span.active').show()
			});
		$('.jcarousel-item-horizontal a').find('span.active').mouseleave(function() {$(this).hide()}).mouseout(function() {$(this).hide()});
	}

	/* ACCORDION */
	if($(".accordion").length) {
		$(".accordion").accordion({
		collapsible: true,
		active: false,
		autoHeight: false,
		header: '.acc_header',
		create: function() {
			if($(this).find('.acc_header').hasClass('active'))
				$(this).accordion("activate", $('.accordion li.acc_header.active').index('.accordion li.acc_header'));
			}
		});
	}

	/* text placeholder */
	$(document).find(".text_placeholder").each(function() {
			
		if (typeof this.onclick != 'function') {return;}

		var placeholder = this.onclick();
		this.onclick = null;
		
		$(this).focus(function() {
			if (this.value == placeholder) {
				this.value = '';
			}
			$(this).parents(".field").addClass("focused");
			focused = true;
		});

		$(this).blur(function() {
			if (!this.value) {
				this.value = placeholder;
			}
			$(this).parents(".field").removeClass("focused");
			focused = false;
		});
	});

	/* Инициализация плейера */
	if (typeof window['audioinit'] == 'function') 
	{
		audioinit();
	}
	
	$(".ceebox").ceebox();

	$("#selectregion").change(function() {
		//alert($(this).val());
		set_cookie('okna_region',$(this).val(), false, false, false, '/', '.okna-etalon.ru');
		document.location.href = document.location.href;
	});

	$("a.taglink").live('click',function(event){
		// Найти нужный якорь
		tag = $(this).html();

		// Свернуть остальные
		/*
		$(".accordion .acc_body").each(function(el){
			if($(this).hasClass('ui-accordion-content-active')) $(this).toggle();
			while($(this).hasClass('ui-accordion-content-active'))
			{
			}
		});
		*/
		//$('.accordion').accordion( "activate" , false );
			
		// Развернуть край
		if ($("a[name='"+tag+"']").parent().css('display') == 'none')
		{
			$("a[name='"+tag+"']").parent().prev().click();
			
			//while(!$("a[name='"+tag+"']").parent().hasClass('ui-accordion-content-active'))
			{
			}
		}
		
		// перейти по якорю
		var val=decodeURI(location.href); 
		var idx=val.indexOf('#');

		if (idx>0)
		{
			val=val.substr(0,idx);
		}
		cmd = "location.href = '"+val+'#'+tag+"'";
		window.setTimeout(docmd, 1000);
	});
	
	setInterval(onchangehash, 100);
});

// Таймер нахождения пользователя на сайте
function onsite()
{
	time = get_cookie('okna-onsite');
	time = time*1 + 1*1;
	set_cookie ('okna-onsite', time)
	if(time == CALLTIME) // открываем предложение консультанта
	{
		$('.popupcall').show();
	}
}

function onsite_no()
{
	$('.popupcall').addClass("click_no");
	cmd = "$('.popupcall').hide();";
	window.setTimeout(docmd, 500);
	
}

function onsite_close()
{
	$('.popupcall').hide();
}

function onsite_yes()
{
	$('.popupcall').addClass("click_yes");
	cmd = "$('.popupcall').hide();$('#aonline').click();";
	window.setTimeout(docmd, 500);
}

var prevhash;
function onchangehash(){
	// если адрес не поменялся
	if(window.location.hash == '') return;
	if(prevhash == window.location.hash) return;
	
	prevhash = window.location.hash;

	// Найти нужный якорь
	tag = window.location.hash.substring(1);

	// Развернуть край
	if ($("a[name='"+tag+"']").parent().css('display') == 'none')
	{
		$("a[name='"+tag+"']").parent().prev().click();
	}
		
	// перейти по якорю
	var val=decodeURI(location.href); 
	var idx=val.indexOf('#');

	cmd = "location.href = location.href";
	window.setTimeout(docmd, 1000);
};
	
function docmd()
{
	eval(cmd);
}

function set_cookie (name, value, expires_year, expires_month, expires_day, path, domain, secure)
{
	var cookie_string = name + "=" + escape(value);
	if (expires_year)
	{
		var expires = new Date (expires_year, expires_month, expires_day);
		cookie_string += "; expires=" + expires.toGMTString();
	}
 
	if (path)
	{
		cookie_string += "; path=" + escape(path);
	}
	else
	{
		cookie_string += "; path=/";
	}
 
	if (domain)
	{
		cookie_string += "; domain=" + escape(domain);
	}
	if (secure)
	{
		cookie_string += "; secure";
	}
	document.cookie = cookie_string;
}

function get_cookie(name)
{
	var prefix = name + "="
    var cookieStartIndex = document.cookie.indexOf(prefix)
	if (cookieStartIndex == -1) return null
	var cookieEndIndex = document.cookie.indexOf(";", cookieStartIndex + prefix.length)
	if (cookieEndIndex == -1) cookieEndIndex = document.cookie.length
    return unescape(document.cookie.substring(cookieStartIndex + prefix.length, cookieEndIndex))
}

