$(document).ready
(
	function()
	{
		/*
		 * Common and main page
		 */
		if ($(".h-interactive-wrap").length)
		{    
            function mycarousel_initCallback(carousel) {
                carousel.buttonNext.click(function() {
                    carousel.startAuto(0);
                });
                carousel.buttonPrev.click(function() {
                    carousel.startAuto(0);
                });
                $(".interactive_small a, .interactive_big li").click(function() {
                    carousel.startAuto(0);
                });
                carousel.clip.hover(function() {
                    carousel.stopAuto();
                }, function() {
                    carousel.startAuto();
                });
            };
            
            $(".interactive_small").jcarousel({
                scroll: 1,
                auto: 5,
                wrap: "circular",
                visible: 4,
                animation: 300,
                initCallback: mycarousel_initCallback
            });
            
            $(".interactive_small a").click(function() {
                window.clearInterval(window.slideshowint);
                $(".interactive_small .active").removeClass("active");
                $(this).parents(".interactive_small li").addClass("active");
                $(".interactive_big li").fadeOut();
                $("#" + $(this).attr("href").slice(1)).fadeIn();
                return false;
            });

            function rotate_bans(){
                var n = $(".interactive_big .active").length && $(".interactive_big .active").next().length ? $(".interactive_big .active").next() : $(".interactive_big li").first();
                $(".interactive_big li").removeClass("active").hide();
                n.addClass("active");
                n.fadeIn();
                $(".interactive_small .active").removeClass("active");
                $(".interactive_small ." + n.attr("id")).closest("li").addClass("active");
            };
            $(".interactive_big li").click(function() {
                window.clearInterval(window.slideshowint);
            });
            rotate_bans();
            window.slideshowint = window.setInterval(rotate_bans, 5300);
        };

        var bul = $('<i class="nbul"></i>');
        $(".nav li li:has('ul') > a").prepend(bul);
        $(".nav li")
            .mouseenter(function() { $(this).addClass("sphover"); })
            .mouseleave(function() { $(this).removeClass("sphover"); });

        /*
         * Common tabs
         */
        if ($(".tabs").length)
        {
        	setTimeout
        	(
        		function()
        		{  
	        		var tabWraps = $('.b-tab');
	        		tabWraps.hide();
	        		tabWraps.first().show();
	        		
	        		$('.tabs li').first().addClass('active');
	        		
	        		$('.tabs a, .b-tab .pager a').click
	        		(
	        				function()
	        				{
	        					var idx = $(this).attr('href');
	        					$('.tabs .active').removeClass('active');
	        					$('.tabs td#' + idx + '-td, .tabs li#' + idx + '-li').addClass('active');
	        					tabWraps.hide();
	        					$($(this).attr('href')).show();
	
	        					tab_hash = idx + '-p';
	        					window.location.hash = tab_hash;

	        					return false;
	        				}
	        		);
	        		
	        		if (window.location.hash.length > 1)
	    			{
	        			$('.tabs a, .b-tab .pager a').each
	    	    		(
	    	    			function(i, ele)
	    	    			{
	    	    				idx = $(this).attr('href');
	    	    				tab_hash = idx + '-p';
	    	    				if (window.location.hash == tab_hash)
	    	    				{
	    	    					$(ele).click();
	    	    				}
	    	    			}
	    	    		);
	    			}
        		},
        		100
        	);
        };
	    
	    $(".h-pager2-wrap").css({"width": $(".pager2").width()});
	    
	    
	    /*
	     * History section
	     */
	    if($(".h-history-wrap").length)
	    {    
	    	$('.h-history-wrap .h-tabs-wrap').tabs
	    	(
	    		{
	    			select: function( event, ui )
	    			{
	    				/*
	    				 * Set location for selected period
	    				 */
	    				new_hash = ui.tab.hash;
	    				hash = window.location.hash;
	    				if (hash.substr(0, new_hash.length) != new_hash)
	    				{
	    					window.location.hash = ui.tab.hash;
	    				}
	    			}
	    		}
	    	);
	    	
	    	$('.h-history-wrap #slider').slider
	    	(
	    		{
	    			min: 0,
	    			max: $('.h-history-wrap .h-tabs-wrap').tabs('length') - 1,
	    			slide: function( event, ui )
	    			{
	    				$('.h-history-wrap .h-tabs-wrap').tabs('select', ui.value);
	    			}
	    		}
	    	); 
	    	
	    	$('.b-history .pager a, .mark a').click
	    	(
	    		function()
	    		{
	    			/*
	    			 * Parse period from item uri and set active period tab
	    			 */
	    			var link;
	    			expr = /#(p[\d]{4}-(?:[\d]{4})?)/;
	    			$(this).attr('href').replace
	    			(
	    				expr,
	    				function (_substr_match, _group_match)
	    				{
	    					link = _group_match;
	    				}
	    			);
	    			$('.h-history-wrap .h-tabs-wrap').tabs('select', link);
	    			
	    			/*
	    			 * Find active tab index and set slider to it
	    			 */
	    			tab_index = $('#' + link + '.b-history').index() - 1;
	    			$('.h-history-wrap #slider').slider('value', tab_index);
	    		}
	    	);
	    	
	    	if (window.location.hash.length > 1)
			{
	    		$('.b-history .pager a, .mark a').each
	    		(
	    			function(i, ele)
	    			{
	    				/*
	    				 * if hash part of location matches href,
	    				 * than process click event
	    				 */
	    				uri = $(ele).attr('href');
	    				hash = window.location.hash;
	    				if (uri.substr(uri.length - hash.length) == hash)
	    				{
	    					$(ele).click();
	    				}
	    			}
	    		);
			}
	    }    

	    
	    /*
	     * FAQ section
	     */
	    if ($('.faq').length)
	    {
		    $('.faq dt a').click
		    (
		    	function()
		    	{
		    		if ($(this).parents('.faq').hasClass('faq-active'))
		    		{
		    			$(this).parents('.faq').removeClass('faq-active');
		    		}
		    		else
		    		{
		    			$(this).parents('.faq').addClass('faq-active');
		    			window.location.hash = $(this).attr('name');
		    		}
		    		return false;
		    	}
		    );
		    
		    $('.tabs a').click
		    (
		    	function()
		    	{
		    		window.location.hash = 'c' + $(this).attr('href').substr(4);
		    	}
		    )

		    category_id = $('.tabs a:eq(0)').attr('href').substr(4);
		    question_id = false;
		    
			if (window.location.hash.length > 1)
			{
				hash_ = window.location.hash.substring(1).split(':');
				for (var i in hash_)
				{
					switch (hash_[i].substr(0, 1))
					{
						case 'c':
							category_id = hash_[i].substr(1);
							break;
						case 'i':
							question_id = hash_[i].substr(1);
							break;
							
					}
					
				}
			}
			
			if (category_id) $('#tab' + category_id + '-td a').click();
			if (question_id) $('#question' + question_id + ' dt a').click();
	    }
	    
	    
	    /*
	     * Photos section
	     */
	    if ($(".scroll-list").length)
	    {

            $(".scroll-list").width(function() {
		    	var kids = $(this).find("li"),
		    	sum_width = 0;
		    	kids.each(function(i, el) {
		    		sum_width += $(el).width();
		    	});
		    	return sum_width;
		    });   
            $(".scroll-pane").jScrollHorizontalPane({
                    scrollbarHeight: 17,
                    scrollbarMargin: 0,
                    resize: false
                });

		    $(".zoom-list").width(function(){
		    	    var kids = $(this).find("li");     
		    	    return kids.length * kids.width();    
		    }); 
	
		    $(".bord").each(function() {$(this).css({"width": $(this).parents(".scroll-list li").width()-5})});
		    $(".jumper").click(function(){
		    	$(".jumper-active").removeClass("jumper-active");
		    	$(this).parents(".scroll-list li").addClass("jumper-active");
		    	var num = $(this).parents("li").prevAll().length;
		    	scroll("-" + $(".zoom-list li:eq(" + num +")").position().left);
		    	return false;
		    });    
	
		    var $galItems = $(".zoom-list li"),
		    oneItemW = $galItems.width(),
		    step = oneItemW,
		    maxLeft = 0,
		    minLeft = ($(".zoom-list").width() - step) * -1,
		    sPane = $(".zoom-wrap2"),
		    $next = $(".znext"),
		    $prev = $(".zprev"),
            thumbs = $(".scroll-list li");
	
		    $prev
		    .mouseenter(function() {
		    	$(this).addClass("zhov").animate({"width":"35px"}, 300);
		    	$(".zprev i").animate({"left":"8px"}, 300);
		    })
		    .mouseleave(function() {
		    	$(this).removeClass("zhov").animate({"width":"27px"}, 300);
		    	$(".zprev i").animate({"left":"4px"}, 300);
		    });
		    $next
		    .mouseenter(function() {
		    	$(this).addClass("zhov").animate({"width":"35px"}, 300);
		    	$(".znext i").animate({"right":"8px"}, 300);
		    })
		    .mouseleave(function() {
		    	$(this).removeClass("zhov").animate({"width":"27px"}, 300);
		    	$(".znext i").animate({"right":"4px"}, 300);
		    });
	
		    function checkState(){
	    		var curpos = Math.floor(sPane.position().left / step) * step;
	
	    		if (curpos == minLeft){
	    			$next.addClass("disabled");
	    		} else {
	    			$next.removeClass("disabled");
	    		}
	
	    		if (curpos == maxLeft){
	    			$prev.addClass("disabled");           
	    		} else {
	    			$prev.removeClass("disabled");
	    		}
		    };
	
		    function forward(){
		    	var idx = Math.floor(sPane.position().left / step),
                 pos = idx * step;

             $(".scroll-list .jumper-active").removeClass("jumper-active");
             $(thumbs.get(Math.abs(idx) + 1)).addClass("jumper-active");
             $(".scroll-pane")[0].scrollTo(".jumper-active");

             scroll(Math.max(pos - step, minLeft));
		    };
	
		    function revers(){
		    	var idx = Math.floor(sPane.position().left / step),
                 pos = idx * step;

             $(".scroll-list .jumper-active").removeClass("jumper-active");
             $(thumbs.get(Math.abs(idx) - 1)).addClass("jumper-active");
             $(".scroll-pane")[0].scrollTo(".jumper-active");

             scroll(Math.min(pos + step, maxLeft));
		    }
	
		    function scroll(targetPos){
		    	sPane.animate({"left":targetPos}, 300, checkState);        
		    }
	
		    $next.click(forward);
		    $prev.click(revers);
		    checkState();
	
		    $(".zoom-wrap2").bind("scroll", checkState);
	
		    window.checkState = checkState;
	    };

        
        /*Video section*/
        if ($(".b-video, .b-tyredescr").length)
        {    
        	$(".b-video .play, .b-video .play-title-link").lightBox({
                overlayOpacity:	0.7,
                containerBorderSize: 15,
                imageLoading: "/i/lightbox-ico-loading.gif",		
	         	imageBtnClose: "/i/lightbox-close.png",		
		        imageBlank: "/i/lightbox-blank.gif"	
            });
            $(".lupa").lightBox({
                overlayOpacity:	0.7,
                containerBorderSize: 15,
                imageLoading: "/i/lightbox-ico-loading.gif",		
	         	imageBtnClose: "/i/lightbox-close.png",		
		        imageBlank: "/i/lightbox-blank.gif"	
            });
        };


        /*Tooltips*/
        if ($(".tooltip_link").length)
        {    
            $(function() {
                $(".tooltip_link").tooltip({
                    bodyHandler: function() {
                                     return $($(this).attr("href")).html();
                                 },
                    showURL: false
                });
            });     
        };

        $(".seasons a").click(function() {
            $(this).closest(".seasons").find(".active").removeClass("active");
            $(this).closest(".seasons li").addClass("active");
            return false;
        });


        if(document.attachEvent){
            $(".zoom-img img").css("padding-top", function() {
                return Math.ceil((420-$(this).height())/2);
            });
        };
        
        
        /*
         * Catalog
         */
        if ($('.h-tyretabs-wrap').length)
        {
        	$('ul.tyredescr-litimg a').click
        	(
        		function()
        		{
        			$('ul.tyredescr-litimg li').removeClass('active');
        			$(this).parents('ul.tyredescr-litimg li').addClass('active');
        			
        			$('.b-tyredescr-bigimg img').attr('src', $(this).attr('href'));
        			$('.b-tyredescr-bigimg a').attr('href', $(this).attr('rel'));
        			        			
        			return false;
        		}
        	)
        	.each
        	(
        		function()
        		{
        			preload_images($(this).attr('href'));
        		}
        	);
        }
    }
);

/*
 * ---------------------
 * Banners functions.
 * 
 */
function ShowBanner(_ele_id, _location_name, _count, _uri)
{
	var holder_obj = document.getElementById(_ele_id);

	$.ajax
	({
		type: 'POST',
		url: '/ajax/show_img.php',     // this is the path from above
		data: 'location_name=' + _location_name + '&count=' + _count + '&uri=' + encodeURIComponent(_uri),
		success: function(s)
		{
			banners_html = s.getElementsByTagName('content')[0].firstChild.nodeValue;
			$(holder_obj).html(banners_html);
		}
	});
}

function message_popup(_text)
{
	alert(_text);
	// $('<div class="message-popup"><span class="close subs-close">&#160;</span><h2>' + _text + '</h2></div>').appendTo('body');
}

function rotate_bigban(_images)
{
	if ($('.b-bigban').length && _images)
	{
		bigban_uri = _images[Math.floor(Math.random() * _images.length)];
		$('.b-bigban').append('<img src="' + bigban_uri + '" alt="" />');
	}
}

var images_cache = [];
function preload_images()
{
	var args_len = arguments.length;
	for (var i = args_len; i--;)
	{
		var cacheImage = document.createElement('img');
		cacheImage.src = arguments[i];
		images_cache.push(cacheImage);
	}
}

function get_numeric_string_ending(_num, _e_1, _e_2, _e_3)
{
	num_str = Math.abs(_num).toString();
	e_1 = typeof(_e_1) != 'undefined' ? _e_1 : '';
	e_2 = typeof(_e_2) != 'undefined' ? _e_2 : 'а';
	e_3 = typeof(_e_3) != 'undefined' ? _e_3 : 'ов';
	
	last_two = num_str.length < 2
		? num_str
		: parseInt(num_str.substr(num_str.length - 2)).toString();
	
	last_one = parseInt(num_str.substr(num_str.length - 1)).toString();
	
	if (last_two == '11' || last_two == '12' || last_two == '13' || last_two == '14')
	{
		return e_3;
	}
	else if (last_one == '2' || last_one == '3' || last_one == '4')
	{
		return e_2;
	}
	else if (last_one == '1')
	{
		return e_1;
	}
	else
	{
		return e_3;
	}
}

function add_social_likes_block(_parent_expr, _like_url) 
{
	vk_button_id = 'vk_like_' + Math.floor(Math.random() * 99999999);
	plus_button_id = 'plusone_' + Math.floor(Math.random() * 99999999);
		
	$(_parent_expr).append
	(
		'<ul id="lightbox-socials">'
			
			// Google Plus
			+ '<li><div id="' + plus_button_id + '" class="g-plusone"></div></li>'
			
			// Odnoklassniki
			// Disabled due to unstable behaviour
			// + '<li><a target="_blank" class="mrc__plugin_uber_like_button" href="http://connect.mail.ru/share?share_url=' + _like_url + '" data-mrc-config="{\'type\' : \'button\', \'caption-mm\' : \'1\', \'caption-ok\' : \'1\', \'width\' : \'190\', \'nc\' : \'1\', \'nt\' : \'1\'}">Нравится</a><script src="http://cdn.connect.mail.ru/js/loader.js" type="text/javascript" charset="UTF-8"></script></li>'
			
			// Twitter
			+ '<li><a href="http://twitter.com/share?url=' + _like_url + '" class="twitter-share-button" data-count="horizontal">Tweet</a><script type="text/javascript" src="http://platform.twitter.com/widgets.js"></script></li>'
			
			// Vkontakte
			+ '<li style="width: 170px;"><div id="' + vk_button_id + '"></div><script type="text/javascript">VK.Widgets.Like("' + vk_button_id + '", {type: "button", pageUrl: "' + _like_url + '"});</script></li>'
			
			// Facebook
			+ '<li style="width: 150px;"><iframe src="http://www.facebook.com/plugins/like.php?app_id=129816070442420&amp;href=' + like_url + '&amp;send=false&amp;layout=button_count&amp;width=150&amp;show_faces=false&amp;action=like&amp;colorscheme=light&amp;font&amp;height=21" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:150px; height:21px;" allowTransparency="true"></iframe></li>'		
		+ '</ul>'
	);
	
	gapi.plusone.render(plus_button_id, {href: _like_url, size: 'medium', count: true});
	
	$('#lightbox-socials').css({'list-style': 'none', position: 'absolute', bottom: '15px', right: 0, 'z-index': 11});
	$('#lightbox-socials li').css({'max-width': '180px', 'margin-left': '5px', display: 'block', float: 'right'});
}

