if (typeof getSelTextWorked == 'undefined'){
	var getSelTextWorked=function(){
		var txt = '';
		if (window.getSelection!=undefined){
			txt = window.getSelection();
		}else if (document.getSelection!=undefined){
			txt = document.getSelection();
		}else if (document.selection!=undefined){
			txt = document.selection.createRange().text;
		}
		return txt;
	}
}

var ua = navigator.userAgent;
var isiPad = /iPad/i.test(ua) || /iPhone OS 3_1_2/i.test(ua) || /iPhone OS 3_2_2/i.test(ua) || /iPod/i.test(ua) || /iPhone/i.test(ua) || /android/i.test(ua);

if (typeof ctrlEnter == 'undefined'){
	var ctrlEnter=function(e)
	{
	    if(((e.keyCode == 13) || (e.keyCode == 10)) && (e.ctrlKey == true)){
			var descr = getSelTextWorked();
		    var feedbackInit = {
		    	'type' : 'error',
		    	'link' : location.href
		    }
		    if (descr != ''){
		    	feedbackInit.messageText = '%ERROR%: "' + descr + '"';
		    }
		    
		    $('a.feedback').feedback(feedbackInit);
	    } else if(e.keyCode == 13){		
			if ($('#captchaBlock').css('display') != 'none'){
				$('#captcha_button').click();
				return false;
			}
		}
	}
}
// JavaScript Document

var urlGrabber = function(){
	var matches = new Array();
	matches = location.href.match(/\#(.*)$/);
	if (matches){
		var link = matches[1];
		if (link.search('http://') != -1){
			return matches[1];
		}
	}
	return false;
}

var showAuthPopup = function(auth_return_url){
    $('#auth_button').click();
	$('#auth_return_url').val(auth_return_url);
    
	return false;
}

	$(document).ready(function() {
		
	$(document).keypress(function(event){ctrlEnter(event)})
		var topNewsFlag = 0;
		var link = urlGrabber();
		if (link){
			$('#NewFeaturedNews div.tabsContainer ul.tabs').find('a.image').each(function(i){
				if ($(this).attr('href').replace('/ua/', '/') == link.replace('/ua/', '/')){
					// afterload all topnews images
					topNewsFlag++;
					showAllTopnewsImages();
					var leftId = $(this).attr('rel');
					$('#NewFeaturedNews').find('div.TabContent').hide();
					$(leftId).show();
					
					var sdvig = 0;
					if (i > $('#NewFeaturedNews div.tabsContainer ul.tabs').find('a.image').size() - 3) {
						sdvig = i-2;
					} else {
						sdvig = i; 
					}
					
					$('#NewFeaturedNews div.tabsContainer ul.tabs').css('top', -92*sdvig);
					$(this).parent().parent().parent().find('li').removeClass('selected');
					$(this).parent().parent().addClass('selected');
				}
			});
			if (!topNewsFlag) {				
				if (link.match(/http\:\/\/[\w-]+\.tochka\.net\/(ua\/)*\d{1,7}-[\w-]+/)){
					location.href = link;
				}
			}
		}

	/* MOUSE OVER AND PRESSDOWN*/
		var buttons = $('span.button_red');
		buttons.mouseover(function(){
			$(this).addClass('MouseOver');
		});
		buttons.mousedown(function(){
			$(this).addClass('MousePressDown');
		});
		buttons.mouseup(function(){
			$(this).removeClass('MousePressDown');
		});
		buttons.mouseleave(function(){
			$(this).removeClass('MouseOver');
			$(this).removeClass('MousePressDown');
		});

	/* MOUSE OVER AND PRESSDOWN*/	
		
		// polls
		$('#poll_form li *').live('click',function(){
			$(this).parent().parent().find('li input').removeAttr('checked');
			$(this).parent().parent().find('li').removeClass('selected');
			$(this).parent().find('input').attr("checked", "checked");
			$(this).parent().addClass('selected');
			return false;
		});
	
		$('div.quickSearch ul.tabs>li').live('click', function(){
			$(this).parent().find('li').removeClass('current');
			$(this).addClass('current');
			if(!$(this).parent().hasClass("disable_pages")) {
				selTab = $(this).find('a').attr('href').replace('#', '');
				$(this).parents('div.quickSearch').find('div.TabContent').hide().filter('#'+selTab).show();
			}
			return false;
		});
		

		$('div.ContentBlock ul.tabs>li:not(.fakeTab)').live('click', function(){
            var customEventName = 'contentBlockTabClick';

			$(this).parent().find('li').removeClass('current');
			$(this).addClass('current');
			var selTab = $(this).find('a').attr('href').replace('#', '');

			if ($(this).parents('div.ContentBlock').hasClass('TVWidget')){
				$(this).parents('div.ContentBlock').find('div.TabContent').hide()
				.filter('#'+selTab).show()
				.find('div.scrollHandleVertical').show()
				;

				$(window).resize();
                $(this).trigger(customEventName, [selTab]);
                return false;

			} else if(!$(this).parent().hasClass("disable_pages")) {
				if ($(this).parents('div.ContentBlock').find('div.TabContent').size() > 0) {
					$(this).parents('div.ContentBlock').find('div.TabContent').hide().filter('#'+selTab).show();
				} else {					
					$(this).parents('div.ContentBlock').find('div.content').hide().filter('#'+selTab).show();
				}
                
                $(this).trigger(customEventName, [selTab]);

				if(!$(this).parent().hasClass("href_action")) {
                    return false;
                }
			}	       
       });


		$('div.quickSearch img.dd_button').live('click', function(){
			$('div.ContentBlock').css({'z-index':'100'});
			$(this).parents('div.ContentBlock').css({'z-index':'110'});
			$(this).parents('li.current').find('div.dropdown').show().addClass('activePopUp');
		});
		$('div.quickSearch div.dropdown img.dd_button').live('click', function(){
			$(this).parents('li.current').find('div.dropdown').hide().removeClass('activePopUp');
		});
		$('div.quickSearch div.dropdown li a').live('click',function(){
			$(this).parent().parent().find("li").show();
			$(this).parent().hide();
			$(this).parents('li.current').find('font').text($(this).text());
			$(this).parents('div.dropdown').hide();
			return false;
		});
	
		$('div.BestPlaces ul.tabs>li').live('click', function(){
			$(this).parent().find('li').removeClass('current');
			$(this).addClass('current')
			selTab = $(this).find('a').attr('href').replace('#', '');
			$(this).parents('div.BestPlaces').find('div.TabContent').hide().filter('#'+selTab).show();
			return false;
		});


		$('div.DropDownElement a.dd_button').live('click', function(){
			$('div.ContentBlock').css({'z-index':'100'});
			$(this).parents('div.ContentBlock').css({'z-index':'110'});
			$(this).parent().find('div.DropDownList').show().addClass('activePopUp');
			$(this).parent().addClass('act_v');
			return false;
		});
		$('div.DropDownElement div.DropDownList li a').live('click',function(){
			$(this).parents('div.DropDownElement').find('font').text($(this).text());
			$(this).parents('div.DropDownList').hide();			
			if (!$(this).parent().parent().parent().hasClass('href_action')){
				return false;
			}
		});

/*
		$('div.select input').click(function(){
			$(this).parent().find('ul:not(.inactive)').toggle();
			$('div.ContentBlock').css({'z-index':'100'});
			$(this).parents('div.ContentBlock').css({'z-index':'110'});
			$(this).parents('div.ContentBlock').find('div.select').css({'z-index':'200'});
			$(this).parents('div.select').css({'z-index':'210'});
		});
*/		
		
		$('div.select input').live('click', function(){
			if($(this).parents('div.select').attr('type')!='select'){ 
			if(isiPad==false){ $(this).parent().find('ul:not(.inactive)').toggle();}
			$('div.ContentBlock').css({'z-index':'100'});
			$(this).parents('div.ContentBlock').css({'z-index':'110'});
			$(this).parents('div.ContentBlock').find('div.select').css({'z-index':'200'});
			$(this).parents('div.select').css({'z-index':'210'});
			

			$('div.Block').css({'z-index':'100'});
			$(this).parents('div.Block').css({'z-index':'110'});
			$(this).parents('div.Block').find('div.select').css({'z-index':'200'});
			$(this).parents('div.select').css({'z-index':'210'});
			if(isiPad){$(this).parents('div.select').find('select').focus();}
			}
		});
		
		$('div.select select').live('change',function(){
			$(this).parents('div.select').find('ul li[key="'+$(this).find('option:selected').attr('value')+'"]').click();
			$(this).parents('div.select').find('input').attr('value',$(this).find('option:selected').attr('value'));
			$(this).parents('div.select').find('input.textfield').attr('value',$(this).find('option:selected').text());
			 setTimeout(function(){ build_select();},1000);
		})
		
		/*$('div.select a').live('click',function(){
				$(this).next().focus();
		});*/
		/*
		$('div.select').mouseleave(function(){
			$(this).find('ul').hide();
		});*/

		$('div.select').live('mouseleave', function(){
			if($(this).attr('type')!='select'){ 
				$(this).find('ul').hide();
			}
		});
		
		/*$('div.select ul li').mouseenter(function(){
			if(!$(this).hasClass('current')) {
				$(this).addClass('current');
				if ($.browser.msie) {
					$(this).parent().animate({opacity: 1.0}, 50); 
				}				
			}
		});*/	
		
		/*$('div.select ul li').live('mouseenter', function(){
			if($(this).parents('div.select').attr('type')!='select'){ 
			if(!$(this).hasClass('current')) {
				$(this).addClass('current');
				if ($.browser.msie) {
					$(this).parent().animate({opacity: 1.0}, 50); 
				}				
			}
			}
		});*/
		
		
		$('div.select ul li').live('mouseleave', function(){
			if($(this).parents('div.select').attr('type')!='select'){ 
				if($(this).hasClass('current')) {
					$(this).removeClass('current');
				}
			}
		});
		
		/*$('div.select ul li').mouseleave(function(){
			if($(this).hasClass('current')) {
				$(this).removeClass('current');
			}
		});*/
		
		$('div.select ul li').live('click', function(){
			//if($(this).parents('div.select').attr('type')=='select'){ 
				$(this).parents('div.select').find('input:text').val($(this).text());
				var key = $(this).attr('key'); 
				//$(this).parent().hide();
				$(this).parents('ul').hide();
				if (key != ''){
					$(this).parents('div.select').find("input[type='hidden']").val(key);
				}
				$(this).trigger('selectLiClick', [key]);
			//}
		});

		/* IE6,7 fix */			
		if (!$.browser.msie || ($.browser.msie && $.browser.version >7))  {
				$('#main:not(.frontpage, .news, .finance) div.Center_2inRow').each(function(){
					var maxHeight = 0;
					var itm = $(this).find('div.ContentBlock div.CB_inner');
					itm.each(function(){
						if ($(this).height() > maxHeight) {
							maxHeight = $(this).height();
						}
					});
					itm.height(maxHeight);
				});
				
				
				$('#main:not(.finance, .blogs) div.ContentBlock').each(function(){
					if ($(this).hasClass('fl') && $(this).next('.fr') && !$(this).hasClass('.with_2_in_col')) {
						var maxHeight = 0;
						var itm = [$(this).find('div.CB_inner'), $(this).next().find('div.CB_inner')];
						$.each(itm, function(){
							if ($(this).height() > maxHeight) {
								maxHeight = $(this).height();
							}
						});
						$.each(itm, function(){
							$(this).height(maxHeight);
						});
					}
					if ($(this).hasClass('.with_2_in_col')) {
						var leftBlock = $(this).find('div.CB_inner'),
							right1 = $(this).next().find('div.CB_inner'),
							right2 = $(this).next().next().find('div.CB_inner');
		
						if (right2.height() + right1.height() + 44 < leftBlock.height()){
							right2.height(leftBlock.height() -  right1.height() - 44);
						} else if (right2.height() + right1.height() + 44 > leftBlock.height()){
							leftBlock.height(right1.height() + right2.height() + 44);
						}
					}
				});
		
				
				$('#main div.EqHeight').each(function(){
					var maxHeight = 0;
					var itm = $(this).find('div.ContentBlock div.CB_inner');
					//indicates if the block with the max height has parent with the .headerOff class
					var headerOff = false;
		
					itm.each(function(){
						if ($(this).height() > maxHeight) {
							maxHeight = $(this).height();
							if($(this).parent().hasClass('headerOff')) {
								headerOff = true;
							}
							else {
								headerOff = false;
							}
						}
					});
		
					itm.each(function(){
						var height = maxHeight;
		
						if(headerOff && !$(this).parent().hasClass('headerOff')) {
							height -= 25;
						}
						else
						if(!headerOff && $(this).parent().hasClass('headerOff')) {
							height += 25;
						}
		
						$(this).css({'min-height' : height});
						if ($.browser.msie && $.browser.version < 7) {
							$(this).css({'height' : height});
						}
		
						var more = $(this).find('.more');
						if(more.length == 1) {
							more.addClass('AbsAlignBottom');
						}
					});			
				});
		}		
		/* IE6,7 fix */	
		
		$('li.gadget').each(function(){
			//$(this).find('ul.tabs li:first').addClass('selected');
			i = 500;
			$(this).find('div.dropdown ul').each(function() {
				$(this).find('li').hide().filter(':first').show()
				$(this).parents('div.top').css('z-index',i);
				i = i-10;
			})
			$(this).find('div.selectBar ul').each(function() {
				$(this).find('li.selected').width($(this).find('a').width()+20);
				$(this).find('li').hide().filter(':first').show()
			})
			$(this).find('div.gadgetTab').hide().filter(':first').show();
		});
		$('li.gadget ul.tabs li').click(function(){
			$(this).parent().find('li').removeClass('selected');
			$(this).addClass('selected');
			var selTab = $(this).find('a').attr('href').replace('#', '');
			$(this).parents('div.content').find('div.gadgetTab').hide().filter('#'+selTab).show();
			return false;
		});


		$('div.NewFeaturedNews ul.tabs li').live('mouseover', function(){
			/*var currElemIndex = $('div.NewFeaturedNews ul.tabs li').index(this);
			var curPos = currElemIndex % allLiSize + 1;
			$('#NewFeaturedNews_counter').text(curPos);*/
			
			// afterload all topnews images
			showAllTopnewsImages();
			$(this).parent().find('li').removeClass('selected');
			$(this).addClass('selected');
			var selTab = $(this).find('div').attr('id').substr(4);
			$(this).parents('div.NewFeaturedNews').find('div.TabContent').hide().filter('#'+selTab).show();
			return false;
		});

		$('div.NewFeaturedNews .button_dwn').live('click',function(){
			var FeatTabs = $('div.NewFeaturedNews ul.tabs'),
				countLi = $(this).parents('div.NewFeaturedNews').find('ul.tabs > li').size(),
				liHeight = $(this).parents('div.NewFeaturedNews').find('ul.tabs > li').height()+parseInt($(this).parents('div.NewFeaturedNews').find('ul.tabs > li').css('marginTop'))+parseInt($(this).parents('div.NewFeaturedNews').find('ul.tabs > li').css('marginBottom')),
				maxTop = (countLi-3)*-liHeight,
				FeatTabsTop = parseInt(FeatTabs.css('top')),
				numLiMoved = countLi-3+FeatTabsTop/liHeight >= 3 ? 3 : countLi-3+FeatTabsTop/liHeight;
			if (FeatTabs.is(':animated')) return false;
			if (FeatTabsTop > maxTop || FeatTabsTop == 0) {
				// afterload all topnews images
				showAllTopnewsImages();
				
				FeatTabs.animate({top: '-='+liHeight*numLiMoved}, 'slow', '', function(){
					var ul = '<ul>'+allLi+'</ul>',
						carusLength = $(ul).find('li').size();
					if (countLi > carusLength){
						FeatTabs.find('li:lt('+(carusLength)+')').remove();
						FeatTabs.css('top', -3*liHeight+'px');
					}
				});
			} else {
				FeatTabs.append(allLi).animate({top: '-='+liHeight*3}, 'slow');
			}
			var n = numLiMoved != 0 ? numLiMoved : 3;
			var current = Math.round((-parseInt(FeatTabs.css('top'))/liHeight + n) % allLiSize+1);
			$('#NewFeaturedNews_counter').text(current + '-' + (current+2));
			
			FeatTabs.find('li.selected').removeClass('selected');
			return false;
		});
		
		$('div.NewFeaturedNews .button_up').live('click',function(){
			var FeatTabs = $('div.NewFeaturedNews ul.tabs'),
				countLi = $(this).parents('div.NewFeaturedNews').find('ul.tabs > li').size(),
				liHeight = $(this).parents('div.NewFeaturedNews').find('ul.tabs > li').height()+parseInt($(this).parents('div.NewFeaturedNews').find('ul.tabs > li').css('marginTop'))+parseInt($(this).parents('div.NewFeaturedNews').find('ul.tabs > li').css('marginBottom')),
				maxTop = (countLi-3)*-liHeight,
				FeatTabsTop = parseInt(FeatTabs.css('top')),
				numLiMoved = countLi-3+(maxTop-FeatTabsTop)/liHeight >= 3 ? 3 : countLi-3+(maxTop-FeatTabsTop)/liHeight;
			if (FeatTabs.is(':animated')) return false;
			if (FeatTabsTop < 0) {
				FeatTabs.animate({top: '+='+liHeight*numLiMoved}, 'slow');
			} else {
				FeatTabs.css('top', -allLiSize*liHeight+'px')
						.prepend(allLi)
						.animate({top: '+='+liHeight*3}, 'slow', '', function(){
					var ul = '<ul>'+allLi+'</ul>',
						carusLength = $(ul).find('li').size();
					FeatTabs.find('li:gt('+(carusLength-1)+')').remove();
				});
			};
			var n = numLiMoved != 0 ? numLiMoved : 3;
			var current = Math.round((-parseInt(FeatTabs.css('top')) / liHeight + (allLiSize-n)) % allLiSize + 1);
			$('#NewFeaturedNews_counter').text(current + '-' + (current+2));
			
			FeatTabs.find('li.selected').removeClass('selected');
			return false;
		});

        $('#main div.GalleryBigImg').mouseover(function(){
                $(this).parent().find('a.btn_prev, a.btn_next').show();
        })
        $('#main div.GalleryBigImg').mouseout(function(){
                $(this).parent().find('a.btn_prev, a.btn_next').hide();
        })

        $('div.selectNew span').live('click', function(){
			if(isiPad==false){$(this).parent().find('ul').toggle();}
			$('div.ContentBlock').css({'z-index':'100'});
			$(this).parents('div.ContentBlock').css({'z-index':'110'});
			$(this).parents('div.ContentBlock').find('div.selectNew').css({'z-index':'200'});
			$(this).parents('div.selectNew').css({'z-index':'210'});
			if(isiPad){$(this).parents('div.selectNew').find('select').focus();}
		});
		$('div.selectNew select').live('change',function(){
			$(this).parents('div.selectNew').find('ul li[key="'+$(this).find('option:selected').attr('value')+'"]').click();
			$(this).parents('div.selectNew').find('input').attr('value',$(this).find('option:selected').attr('value'));
			$(this).parents('div.selectNew').find('span.selectedValue').attr('value',$(this).find('option:selected').text());
			 setTimeout(function(){ build_select();},1000);
		})
		$('div.selectNew').bind('mouseleave', function(){
			$(this).find('ul').hide();
			$(this).find('li').removeClass('current');
		});
		$('div.selectNew ul li').bind('mouseenter', function(){
			$(this).addClass('current');
			if ($.browser.msie) {
				$(this).parent().animate({opacity: 1.0}, 50);
			}
		});
		$('div.selectNew ul li').bind('mouseleave', function(){
			$(this).removeClass('current');
		});
		$('div.selectNew ul li').live('click', function(){
			$(this).parents('div.selectNew').find('span.selectedValue').html($(this).html());
            var key = $(this).attr('key');
			$(this).parents('div.selectNew').find('input').val(key);
			$(this).parent().hide();
            $(this).trigger('selectNewLiClick', [key]);
		});

		$('table.RatesDataTable').each(function(){
			$(this).find('tr:last').css({'background-image' : 'none'});
		});
		$('table.switchableRows').each(function(){
			$(this).find('tr:first th:last').css({'border-right' : '#f8de75 1px solid'});
		});

		$('table.switchableRows tr:not(.selected, .headerTR)').live('click',function(){
			/*selTab = $(this).attr('id').replace('T_', '');;
			$(this).parents('div.content').find('div.RatesGraphics').hide().filter('#'+selTab).show();*/

			$(this).parents('table').find('tr.selected').prev().removeClass('noneBG');
			$(this).parents('table').find('tr.selected').removeClass('selected');
			$(this).parents('table').find('tr td').css({'border-bottom' : '#cccccc 0px dashed'});

			$(this).addClass('selected');
			$('table.switchableRows tr.selected').each(function(){
				$(this).parents('table').find('tr').find('td:first').css({'border-left' : '#f8de75 0px solid'});
				$(this).parents('table').find('tr').find('td:last').css({'border-right' : '#f8de75 1px solid'});
				$(this).find('td:first').css({'border-left' : '#f8de75 1px solid'});
				$(this).find('td:last').css({'border-right' : '#fffcea 1px solid'});
				$(this).prev().addClass('noneBG');
				$(this).parents('table').find('tr:last td').css({'border-bottom' : '#fff 0px solid'});
			});
		});
		
        $('table.switchableRows.hoverable tr').bind('mouseenter',function(){
            if(!$(this).hasClass('selected') && !$(this).hasClass('headerTR')) {
                $(this).siblings('tr.selected')
                           .prev()
                           .removeClass('noneBG')
                       .end()
                           .removeClass('selected');

                $(this).siblings('tr')
                           .find('td')
                           .css({'border-bottom' : '#cccccc 0px dashed'});

                $(this).addClass('selected');

                $(this).siblings('tr')
                           .find('td:first')
                           .css({'border-left' : '#f8de75 0px solid'})
                       .end()
                           .find('td:last')
                           .css({'border-right' : '#f8de75 1px solid'});

                $(this)
                    .find('td:first')
                    .css({'border-left' : '#f8de75 1px solid'})
                .end()
                    .find('td:last')
                    .css({'border-right' : '#fffcea 1px solid'})
                .end()
                    .prev()
                    .addClass('noneBG')
                .end()
                    .siblings('tr:last')
                        .find('td')
                        .css({'border-bottom' : '#fff 0px solid'});
            }
        }); 
		
		$('table.switchableRows tr.selected').each(function(){
			$(this).parents('table').find('tr').find('td:first').css({'border-left' : '#f8de75 0px solid'});
			$(this).parents('table').find('tr').find('td:last, th:last').css({'border-right' : '#f8de75 1px solid'});
			$(this).find('td:first').css({'border-left' : '#f8de75 1px solid'});
			$(this).find('td:last').css({'border-right' : '#fffcea 1px solid'});
			$(this).prev().find('td').css({'border-bottom' : '#f8de75 1px solid'});
		});
		$('#main .rightColumn .CurrencyWidget').each(function(){
			if ($(this).find('table.RatesDataTable').height() > $(this).find('div.RatesGraphics').height()-3) {
				$(this).find('div.RatesGraphics').height($(this).find('table.RatesDataTable').height()-3);
			}
			if ($.browser.msie && $.browser.version < 7) {
				$(this).find('div.content').height($('.RatesGraphics').height()-4);
			}
		});

		$('#stripedates').find('li a').click(function(){
			location.href = $(this).attr('href');
		});

		if (typeof $.fn.feedback == 'undefined'){
		// Feedback



		$.fn.feedback = function(options){
			var domain = typeof mainDomainHttp != 'undefined' ? mainDomainHttp : 'http://tochka.net/',
				activeTab = typeof options != 'undefined' && typeof options.type != 'undefined' ? 'activeTab='+options.type : '',
				messageText = typeof options != 'undefined' && typeof options.messageText != 'undefined' ? '&messageText='+options.messageText : '',
				link = typeof options != 'undefined' && typeof options.link != 'undefined' ? '&fback_location='+options.link : '';
			$.getScript(domain+'feedbackform/?' + activeTab + messageText + link,
				function(){
					if ($('div.feedback').children().length == 0){
						$('body').append(feedback_form.data);
					} else {
						$('div.feedback').replaceWith(feedback_form.data);
					}
					$('div.feedback').each(setFeedback);
				}
			);
		};
		var setFeedback = function(){
			var self = this;
			var con = $(self).children(".c");
			$(self).children(".opacity").height($(document).height());
			//	$(window).resize(function(){
			//		$(self).height($(document).height());
			//	});
			$(con).css({
				marginTop: function(){
					return parseInt($(con).height()/-2);
				},
				marginLeft: '-240px'
		  	});
			$('div.feedback').find("a.fback_close, input.fback_close").live('click',function(){
				$('div.feedback').remove();
			});
			$(self).find("ul.tabsLeft").tabs();
		};
		/* Automatically apply to any a.feedback */
		$('a.feedback').click(function(){
			$(this).feedback();
		});

		/* Restrict pushing the enter button in email field*/
		$('#fback_email').live('click',function(){
		$("input[name='fback_email']").keypress(function(e){
			if (e.which == 13)
				return false;
			 else
				return true;
		});
		});
		
		// Feedback	
		$('#fback_submit').live('click',function(){
			var fback_text = $('#fback_text').val(),
				fback_type = $('div.feedback').find('ul.tabsLeft').find('li.active').attr('id'),
				fback_email = $('#fback_email').val();
			if (fback_text.trim() == ''){
				alert(typeof feedback_validate_message != 'undefined' ? feedback_validate_message : 'Поле "Текст сообщения" не заполнено');
				return false;
			}
			if (fback_email.trim() == '' || !validate_email(fback_email.trim())){
				alert(typeof feedback_validate_email != 'undefined' ? feedback_validate_email : 'Поле Email не заполнено или заполнено некорректно');
				return false;
			}
			$.post(_LANG_URL + '/feedbacksend/', {
				'fback_email': fback_email,
				'fback_type': fback_type,
				'fback_text': fback_text,
				'fback_location': location.href
			}, function(data){
				$('div.feedback').replaceWith(data);
				$('div.feedback').find("div.opacity").height($(document).height());
				$('div.feedback').find('div.c').css({
					marginTop: function(){
						return parseInt($(this).height()/-2);
					},
					marginLeft:  function(){
						return parseInt($(this).width()/-2);
					}
			  	});
			});
		});
		}
		
		
		/*
		* Script for show/hide tags.
		*/
		$("#show-tags").click(function(){
			$("#tags-short").hide();
            $("#tags-long").show();
			return false;
		});

		$("#hide-tags").click(function(){
			$("#tags-long").hide();
			$("#tags-short").show();
			return false;
		});

		/*
		* Script for show/hide tags in news.
		*/
		$("#showtags").click(function(){
			$(this).hide();
            $("#tags-long").show('slow').css('display', 'inline');
			return false;
		});

		$("#hidetags").click(function(){
			$("#tags-long").hide();
			$("#showtags").show();
			return false;
		});
		
		
		if(isiPad){ build_select();}
	});

	function build_select(){
		$('div.select, div.selectNew').each(function(){
			var list_li = '';
			$(this).css({ position:'relative'});
			$(this).find('ul li').each(function(){
				list_li += '<option value="'+$(this).attr('key')+'">'+$(this).text()+'</option>';
			});
			$(this).find('select').remove();
			$(this).append('<select style="position:absolute; opacity:0; top:0;left:0;">'+list_li+'</select>');
		});
	}
  var carouselCombine = function(info)
  {
    if(info.carusel==Object)
      $carusel=$(info.carusel);
    else if(info.id==undefined)
      return false
    else
      $carusel=$('#'+info.id);

    if(info.btn_prev == undefined)
      info.btn_prev='.btn_prev'
    if(info.btn_next == undefined)
      info.btn_next='.btn_next'
    if(info.list == undefined)
      info.list='ul:first';
    
    var $btn_prev=$carusel.find(info.btn_prev)
    var $btn_next=$carusel.find(info.btn_next)
    var $list=$carusel.find(info.list)


    info.caruselWidth=$carusel.width();
    info.caruselHeight=$carusel.height();
    info.listWidth=$list.width()
    info.listHeight=$list.height()
    
    info.position=1;
    info.pageNum=1;
    
    if((info.orient == undefined && info.listHeight<=info.listWidth ) || info.orient=='hori') 
      info.sift='left'
    else
      info.sift='top';

    if(info.countEl == undefined )
      info.countEl =$list.find('li').size();
    

    if(info.sift=='left')
    {
      if(info.listSize == undefined)
        info.listSize=info.listWidth
      if(info.visibleSize == undefined)
        info.visibleSize=info.caruselWidth
    }
    else
    {
      if(info.listSize == undefined)
        info.listSize=info.listHeight
      if(info.visibleSize == undefined)
        info.visibleSize=info.caruselHeight
    }

    if(info.elSize == undefined)
      info.elSize=Math.round(info.listSize/info.countEl)


    if(info.countViewEl == undefined )
      info.countViewEl=Math.round(info.visibleSize/info.elSize);

    if(info.infinite == undefined)
    {
      if(info.countEl/info.countViewEl>=2)
      {
        info.infinite = true;
      }
      else
      {
        info.infinite = false
        if(info.countElSift == undefined)
          info.countElSift =1;
        info.pageCount=Math.ceil((info.countEl-info.countViewEl)/info.countElSift)+1
      }
    }

    if(info.countElSift == undefined)
      info.countElSift =info.countViewEl

      if(info.siftSize == undefined)
      info.siftSize=info.countElSift*info.elSize

    if(info.infinite == undefined)
      info.infinite = true;
    else if( info.pageCount == undefined && info.infinite == false)
      info.pageCount=Math.ceil((info.countEl-info.countViewEl)/info.countElSift)+1
      
    if(info.pageCount == undefined)
      info.pageCount=0

    if(!info.infinite || info.pageCount!=0)
      $btn_prev.css({'visibility': 'hidden'});
  







    $btn_next.live('click',function(){
      if ($list.is(':animated')) 
        return false;
      info.pageNum++;
      $btn_prev.css({'visibility': 'visible'})
      act={}
      if(info.pageCount>0 && info.pageNum==info.pageCount)
        $btn_next.css({'visibility': 'hidden'});
      if(info.pageCount>0 && info.countEl<info.countViewEl+info.countElSift+info.position-1)
      {
        countElSift=info.countEl-info.countViewEl-info.position+1
        info.position+=countElSift
        act[info.sift]='-='+(countElSift*info.elSize)
        $orig=$list.find('li:lt('+countElSift+')')
      }
      else
      {
        info.position+=info.countElSift
        act[info.sift]='-='+info.siftSize
        $orig=$list.find('li:lt('+info.countElSift+')')
      }
      $clon=$orig.clone();

      $list.width(info.listSize + info.siftSize)
      .append($clon)
      .animate(act, 'slow', '',function(){
        $clon.remove();
        $orig.appendTo($list)
        $list.css(info.sift, 0)
      });
      if(info.counterel != undefined){
        $(info.counterel).html(info.position);
      }
      return false;
    })
    
    $btn_prev.live('click',function(){
      if ($list.is(':animated')) 
        return false;
      info.pageNum--;
      act={}
      $btn_next.css({'visibility': 'visible'})
      if(info.pageCount>0 && info.pageNum==1)
        $btn_prev.css({'visibility': 'hidden'});
      
      if(info.pageCount>0 && info.position<=info.countElSift)
      {
        countElSift=info.position-1
        info.position-=countElSift;

        siftSize=countElSift*info.elSize
        act[info.sift]='+='+(siftSize)+'px'
        $orig=$list.find('li:gt('+(info.countEl-1-countElSift)+')')
        $clon=$orig.clone();
        
        $list.width(info.listSize + siftSize)
        .prepend($clon)
        .css(info.sift, '-'+siftSize+'px')
        .animate(act, 'slow', '',function(){
          $list.prepend($orig)
           .css(info.sift, 0)
          $clon.remove();
        })
      }
      else
      {
        info.position-=info.countElSift;
        act[info.sift]='+='+info.siftSize+'px'
        $orig=$list.find('li:gt('+(info.countEl-1-info.countElSift)+')')
        $clon=$orig.clone();
        $list.width(info.listSize + info.siftSize)
          .css(info.sift, '-'+info.siftSize+'px')
          .prepend($clon)
          .animate(act, 'slow', '',function(){
            $list.prepend($orig).css(info.sift, 0)
            $clon.remove();
        });
      }
      if(info.counterel != undefined){
        $(info.counterel).html(info.position);
      }      
      return false;
    })
  }
	
var carouselMN = function(block){
	$('#'+block.id+' .btn_next').live('click',function(){
		var jokesCarusel = $(this).parent().parent().find('.carousel_container ul'),
			countLi = jokesCarusel.find('li').size(),
			liWidth = block.li_width,
			maxLeft = (countLi-1*block.li_in_row)*-liWidth,
			carusLeft = jokesCarusel.css('left') == 'auto' ? 0 :parseInt(jokesCarusel.css('left')),
			temp = jokesCarusel.html();
		if (jokesCarusel.is(':animated')) return false;
		//var ids = new Array();
		var addedLi = '';
		for (var i=0; i<block.li_per_time; i++){
			//ids[ids.length] = (i+block.right%countLi+countLi)%countLi;
			addedLi += block.elements[(i+block.right%countLi+countLi)%countLi];
		}
		//alert(ids.join());
		jokesCarusel
			.width(jokesCarusel.width() +  block.li_per_time * liWidth)
			.append(addedLi)
			.animate({left: '-='+liWidth*block.li_per_time}, 'slow', '', function(){
				jokesCarusel
					.css('left', 0)
					.width(jokesCarusel.width() -  block.li_per_time * liWidth)
					.find('li:lt('+block.li_per_time+')').remove();				
				block.right += block.li_per_time;
				block.left += block.li_per_time;
			});
		return false;
	});
	$('#'+block.id+' .btn_prev').live('click',function(){
		var jokesCarusel = $(this).parent().parent().find('.carousel_container ul'),
			countLi = jokesCarusel.find('li').size()
			carusLeft = jokesCarusel.css('left') == 'auto' ? 0 :parseInt(jokesCarusel.css('left')),
			liWidth = block.li_width,
			temp = jokesCarusel.html(),
			addedLi = '';
		if (jokesCarusel.is(':animated')) return false;
		for (var i = countLi+block.left-block.li_per_time; i<countLi+block.left; i++){
			addedLi += block.elements[(countLi+(i%countLi))%countLi];
		}
		jokesCarusel.prepend(addedLi);
		var newLeft = -block.li_per_time*liWidth;
		jokesCarusel
			.css('left', newLeft)
			.width(jokesCarusel.width() +  block.li_per_time * liWidth)
			.animate({left: '+='+liWidth*block.li_per_time}, 'slow', '', function(){
				jokesCarusel
					.width(jokesCarusel.width() -  block.li_per_time * liWidth)
					.find('li:gt('+(countLi-1)+')').remove();
				block.left -= block.li_per_time;
				block.right -= block.li_per_time;
			});
		return false;
	});
}
	
var carousel = function(block){
	$('#'+block.id+' .btn_next').live('click',function(){
		var jokesCarusel = $(this).parent().parent().find('.carousel_container ul:first'),
			countLi = jokesCarusel.children('li').size(),
			liWidth = block.li_width,
			maxLeft = (countLi-1*block.li_in_row)*-liWidth,
			carusLeft = jokesCarusel.css('left') == 'auto' ? 0 :parseInt(jokesCarusel.css('left')),
			temp = jokesCarusel.html();
			
			infinite_next = ((countLi+block.li_in_row)-(block.li_in_row*$('#'+block.counter_id).text()));
			
		if((infinite_next <= block.li_in_row) && ($('#'+block.infinite).selector=='#false')){return false;}
			
		if (jokesCarusel.is(':animated')) return false;
		if (carusLeft > maxLeft || (carusLeft == 0 && countLi != 1) || (carusLeft == -liWidth*block.li_in_row && countLi/block.li_in_row != 2)) {
	
			jokesCarusel.animate({left: '-='+liWidth*block.li_in_row}, 'slow');
			
			$('#'+block.counter_id).text(parseInt($('#'+block.counter_id).text())+1);

			$(this).parent().find('a.notAble').removeClass('notAble');
		} else if (carusLeft < maxLeft) {
			jokesCarusel.animate({left: '-='+liWidth*block.li_in_row}, 'slow');

			$(this).addClass('notAble');
		} else {
			jokesCarusel
				.width(jokesCarusel.width()*2)
				.append(temp)
				.animate({left: '-='+liWidth*block.li_in_row}, 'slow', '', function(){
					jokesCarusel
						.width(jokesCarusel.width()/2)
						.css('left', '0px')
						.find('li:lt('+countLi+')').remove();
				});
			$('#'+block.counter_id).text(1);
		}
		if (typeof(block.function_next) == 'function'){
			(block.function_next)();
		}		
		return false;
	});
	$('#'+block.id+' .btn_prev').live('click',function(){
		var jokesCarusel = $(this).parent().parent().find('.carousel_container ul:first'),
			countLi = jokesCarusel.children('li').size(),
			carusLeft = jokesCarusel.css('left') == 'auto' ? 0 :parseInt(jokesCarusel.css('left')),
			liWidth = block.li_width,
			temp = jokesCarusel.html();
			
			if(($('#'+block.counter_id).text()==1) && ($('#'+block.infinite).selector=='#false')){return false;}
			
			
		if (jokesCarusel.is(':animated')) return false;
		if (carusLeft == -liWidth) {
			jokesCarusel.animate({left: '+='+liWidth*block.li_in_row}, 'slow');

			$('#'+block.counter_id).text(parseInt($('#'+block.counter_id).text())-1);
			
			$(this).addClass('notAble');
		} else if (carusLeft < 0 || jokesCarusel.find('li:first').children().length == 0) {
			jokesCarusel.animate({left: '+='+liWidth*block.li_in_row}, 'slow');

			$('#'+block.counter_id).text(parseInt($('#'+block.counter_id).text())-1);

			$(this).parent().find('a.notAble').removeClass('notAble');
			if (carusLeft == -liWidth) {
				$(this).addClass('notAble');
			}
		} else {
			jokesCarusel
				.width(jokesCarusel.width()*2)
				.prepend(temp)
				.css('left', liWidth*(-countLi)+'px')
				.animate({left: '+='+liWidth*block.li_in_row}, 'slow', '', function(){
					jokesCarusel
						.width(jokesCarusel.width()/2)
						.find('li:gt('+(countLi-1)+')').remove();
				});
			$('#'+block.counter_id).text(countLi/block.li_in_row);
		}
		if (typeof(block.function_prev) == 'function'){
			(block.function_prev)();
		}			
		return false;
	});
}

var video_carousel = function(block){
	$('#'+block.id+' .btn_next').live('click',function(){
		var counter = $('#'+block.counter_id),
			counterVal = parseInt(counter.text());
		if (counterVal != block.countLi){
			counter.text(counterVal+1);
		} else {
			counter.text('1');
		}
		if (typeof(block.function_next) == 'function'){
			(block.function_next)();
		}		
		return false;
	});
	$('#'+block.id+' .btn_prev').live('click',function(){
		var counter = $('#'+block.counter_id),
			counterVal = parseInt(counter.text());
		if (counterVal != 1){
			counter.text(counterVal-1);
		} else {
			counter.text(block.countLi);
		}
		if (typeof(block.function_prev) == 'function'){
			(block.function_prev)();
		}			
		return false;
	});
}



var carouselAjaxSearchGalleries = function(block){

    $('#'+block.id+' .btn_next').live('click',function(){
        var jokesCarusel = $('#'+block.ulId),
        	countLi = jokesCarusel.find('li').size(),
			offset = parseInt($('#'+block.counter_id).text()),
			total = parseInt($('#'+block.total_id).text()),
        	liWidth = block.li_width;
        if (jokesCarusel.is(":animated")) return false;

		if (total - offset >= block.li_per_time){
			movedItems = block.li_per_time;
		} else {
			movedItems = total - offset;
		}
		if (movedItems == 0){
			offset = 0;
			movedItems = block.li_per_time;
		}
		$.get(block.url + offset, block.GET_params, function(data){
			var start_offset = block.li_in_row == data.countItems ? block.li_in_row : data.countItems;
			
			$('#'+block.begin_counter_id).text(offset+1 - (block.li_per_time - movedItems));
			$('#'+block.counter_id).text(offset + start_offset);
		
			jokesCarusel.append(data.content);
			countLi = jokesCarusel.find('li').size();
			jokesCarusel.width(liWidth * countLi);
			
		}, 'json');
		jokesCarusel.animate({left: '-='+liWidth * movedItems}, 'slow', '', function(){
			jokesCarusel.width(liWidth * block.li_per_time);
			jokesCarusel.css('left', 0);
			jokesCarusel.find('li:lt('+movedItems+')').remove();
		});
        return false;
    });

    $('#'+block.id+' .btn_prev').live('click',function(){
        var jokesCarusel = $('#'+block.ulId),
        	countLi = jokesCarusel.find('li').size(),
			offset = parseInt($('#'+block.counter_id).text()),
			total = parseInt($('#'+block.total_id).text()),
        	liWidth = block.li_width;
        if (jokesCarusel.is(":animated")) return false;

		if (offset <= block.li_per_time){
			movedItems = offset;
			offset = total - offset;
		} else {
			movedItems = block.li_per_time;
			offset = offset - 2 * block.li_per_time;
		}		
		if (offset < 0){
			offset = 0;
			movedItems = block.li_per_time;
		}
		$.get(block.url + offset, block.GET_params, function(data){
			var start_offset = block.li_in_row == data.countItems ? block.li_in_row : data.countItems;
			
			$('#'+block.begin_counter_id).text(offset+1 - (block.li_per_time - movedItems));
			$('#'+block.counter_id).text(offset + start_offset);
		
			jokesCarusel
				.width(liWidth * movedItems*2)
				.prepend(data.content)
				.css('left', liWidth*(-movedItems)+'px')
				.animate({left: '+='+liWidth*movedItems}, 'slow', '', function(){
					jokesCarusel
						.width(liWidth * movedItems)
						.find('li:gt('+(countLi-1)+')').remove();
				});
		}, 'json');		
        return false;
    });	
}

var carouselAjaxSearchArticles = function(block){

    $('#'+block.id+' .btn_next').live('click',function(){
        var jokesCarusel = $('#'+block.ulId),
        	countLi = jokesCarusel.children('li').size(),
			offset = parseInt($('#'+block.counter_id).text()),
			total = parseInt($('#'+block.total_id).text()),
        	liWidth = block.li_width;
        if (jokesCarusel.is(":animated")) return false;

		if (total - offset >= block.li_per_time){
			movedItems = block.li_per_time;
		} else {
			movedItems = total - offset;
		}
		if (movedItems == 0){
			offset = 0;
			movedItems = block.li_per_time;
		}
		$.get(block.url + offset, block.GET_params, function(data){
			var start_offset = block.li_in_row == data.countItems ? block.li_in_row : data.countItems;
			
			$('#'+block.begin_counter_id).text(offset+1);
			$('#'+block.counter_id).text(offset + start_offset);
		
			jokesCarusel.append(data.content);
			countLi = jokesCarusel.children('li').size();
			jokesCarusel.width(liWidth * countLi);
			
		}, 'json');
		jokesCarusel.animate({left: '-='+liWidth * movedItems}, 'slow', '', function(){
			jokesCarusel.width(liWidth * block.li_per_time);
			jokesCarusel.css('left', 0);
			jokesCarusel.find('li:lt('+movedItems+')').remove();
		});
        return false;
    });

    $('#'+block.id+' .btn_prev').live('click',function(){
        var jokesCarusel = $('#'+block.ulId),
        	countLi = jokesCarusel.children('li').size(),
			offset = parseInt($('#'+block.counter_id).text()),
			total = parseInt($('#'+block.total_id).text()),
        	liWidth = block.li_width;
        if (jokesCarusel.is(":animated")) return false;

		if (offset <= block.item_in_li){
			movedItems = offset;
			offset = total - offset;
		} else {
			movedItems = block.li_per_time;
			offset = offset - 2 * block.item_in_li;
		}		

		if (offset < 0){
			offset = 0;
			movedItems = block.li_per_time;
		}
		$.get(block.url + offset, block.GET_params, function(data){
			var start_offset = block.item_in_li == data.countItems ? block.item_in_li : data.countItems;
			
			$('#'+block.begin_counter_id).text(offset+1);
			$('#'+block.counter_id).text(offset + start_offset);
		
			jokesCarusel
				.width(liWidth * movedItems*2)
				.prepend(data.content)
				.css('left', liWidth*(-movedItems)+'px')
				.animate({left: '+='+liWidth*movedItems}, 'slow', '', function(){
					jokesCarusel
						.width(liWidth * movedItems)
						.find('li:gt('+(countLi-1)+')').remove();
				});
		}, 'json');		
        return false;
    });	
}

var carouselAjaxSearchArticles2 = function(block){

    $('#'+block.id+' .BtnNext').live('click',function(){
        var jokesCarusel = $('#'+block.ulId),
        	countLi = jokesCarusel.children('li').size(),
			offset = parseInt($('#'+block.counter_id).text()),
			total = parseInt($('#'+block.total_id).text()),
        	liWidth = block.li_width;
        if (jokesCarusel.is(":animated")) return false;

		if (total - offset >= block.li_per_time){
			movedItems = block.li_per_time;
		} else {
			movedItems = total - offset;
		}
		if (movedItems == 0){
			offset = 0;
			movedItems = block.li_per_time;
		}
		$.get(block.url + offset, block.GET_params, function(data){
			var start_offset = block.li_in_row == data.countItems ? block.li_in_row : data.countItems;

			$('#'+block.begin_counter_id).text(offset+1);
			$('#'+block.counter_id).text(offset + start_offset);

			jokesCarusel.append(data.content);
			countLi = jokesCarusel.children('li').size();
			jokesCarusel.width(liWidth * countLi);

		}, 'json');
		jokesCarusel.animate({left: '-='+liWidth * movedItems}, 'slow', '', function(){
			jokesCarusel.width(liWidth * block.li_per_time);
			jokesCarusel.css('left', 0);
			jokesCarusel.find('li:lt('+movedItems+')').remove();
		});
        return false;
    });

    $('#'+block.id+' .BtnPrev').live('click',function(){
        var jokesCarusel = $('#'+block.ulId),
        	countLi = jokesCarusel.children('li').size(),
			offset = parseInt($('#'+block.counter_id).text()),
			total = parseInt($('#'+block.total_id).text()),
        	liWidth = block.li_width;
        if (jokesCarusel.is(":animated")) return false;

		if (offset <= block.item_in_li){
			movedItems = offset;
			offset = total - offset;
		} else {
			movedItems = block.li_per_time;
			offset = offset - 2 * block.item_in_li;
		}

		if (offset < 0){
			offset = 0;
			movedItems = block.li_per_time;
		}
		$.get(block.url + offset, block.GET_params, function(data){
			var start_offset = block.item_in_li == data.countItems ? block.item_in_li : data.countItems;

			$('#'+block.begin_counter_id).text(offset+1);
			$('#'+block.counter_id).text(offset + start_offset);

			jokesCarusel
				.width(liWidth * movedItems*2)
				.prepend(data.content)
				.css('left', liWidth*(-movedItems)+'px')
				.animate({left: '+='+liWidth*movedItems}, 'slow', '', function(){
					jokesCarusel
						.width(liWidth * movedItems)
						.find('li:gt('+(countLi-1)+')').remove();
				});
		}, 'json');
        return false;
    });
}


/*
 * Same as carousel(), but this version takes into consideration only the ul
 * elements that are children of .carousel_container; same with li elements,
 * so the carousel won't break when its elements in turn contain lists of
 * elements. It'll also return false early if the list has only one li element
 * (that is, nothing will happen when btn_next, btn_prev are clicked).
 */
var carouselV2 = function(block){
	$('#'+block.id+' .btn_next').live('click',function(){
		var carousel = $(this).parent().parent().find('.carousel_container > ul'),
			countLi = (typeof(block.count_li) == 'undefined')?carousel.children('li').length:block.count_li,
			liWidth = block.li_width,
			maxLeft = (countLi-1*block.li_in_row)*-liWidth,
			carusLeft = carousel.css('left') == 'auto' ? 0 : parseInt(carousel.css('left'));

		if (countLi == 1 || carousel.is(':animated')) return false;
		if (carusLeft > maxLeft || (carusLeft == 0 && countLi != 1) || (carusLeft == -liWidth*block.li_in_row && countLi != 2)) {
			carousel.animate({left: '-='+liWidth*block.li_in_row}, 'slow');

			if(block.counter_id) {
                $('#'+block.counter_id).text(parseInt($('#'+block.counter_id).text())+1);
            }

            if(block.notCyclic) {
            	if ((carusLeft - block.li_in_row*liWidth) == maxLeft){
                  $(this).hide();
            	}
                $(this).parent().find('.btn_prev').show();
            }

		} else if (carusLeft < maxLeft) {
			carousel.animate({left: '-='+liWidth*block.li_in_row}, 'slow');

			$(this).addClass('notAble');
		} else if(!block.notCyclic) {
            var temp = carousel.html();

			carousel
				.width(carousel.width()*2)
				.append(temp)
				.animate({left: '-='+liWidth*block.li_in_row}, 'slow', '', function(){
					carousel
						.width(carousel.width()/2)
						.css('left', '0px')
						.children('li:lt('+countLi+')').remove();
				});
                
            if(block.counter_id) {
                $('#'+block.counter_id).text(1);
            }
		}
		if (typeof(block.function_next) == 'function'){
			(block.function_next)();
		}
		return false;
	});
	$('#'+block.id+' .btn_prev').live('click',function(){
		var carousel = $(this).parent().parent().find('.carousel_container > ul'),
		    countLi = (typeof(block.count_li) == 'undefined')?carousel.children('li').length:block.count_li,
			carusLeft = carousel.css('left') == 'auto' ? 0 :parseInt(carousel.css('left')),
			liWidth = block.li_width;
            
		if (countLi == 1 || carousel.is(':animated')) return false;
		if (carusLeft == -liWidth*block.li_in_row) {
			carousel.animate({left: '+='+liWidth*block.li_in_row}, 'slow');

			if(block.counter_id) {
                $('#'+block.counter_id).text(parseInt($('#'+block.counter_id).text())-1);
            }

            if(block.notCyclic) {
                $(this).hide();
                $(this).parent().find('.btn_next').show();
            }

			$(this).addClass('notAble');
		} else if (carusLeft < 0 || carousel.find('li:first').children().length == 0) {
			carousel.animate({left: '+='+liWidth*block.li_in_row}, 'slow');

            if(block.counter_id) {
                $('#'+block.counter_id).text(parseInt($('#'+block.counter_id).text())-1);
            }

            $(this).parent().find('.btn_next').show();
			if (carusLeft == -liWidth) {
				$(this).addClass('notAble');
			}
		} else if(!block.notCyclic) {
            var temp = carousel.html();

			carousel
				.width(carousel.width()*2)
				.prepend(temp)
				.css('left', liWidth*(-countLi)+'px')
				.animate({left: '+='+liWidth*block.li_in_row}, 'slow', '', function(){
					carousel
						.width(carousel.width()/2)
						.children('li:gt('+(countLi-1)+')').remove();
				});
			$('#'+block.counter_id).text(countLi/block.li_in_row);
		}
		if (typeof(block.function_prev) == 'function'){
			(block.function_prev)();
		}
		return false;
	});
}

var carouselAJAX = function(block){
    $('#'+block.id+' .btn_next').live('click',function(){
        var jokesCarusel = $(this).parent().parent().find('.carousel_container ul'),
        	countLi = jokesCarusel.find('li').size(),
        	liWidth = block.li_width,
        	maxLeft = (countLi-1*block.li_in_row)*-liWidth,
        	carusLeft = jokesCarusel.css('left') == 'auto' ? 0 :parseInt(jokesCarusel.css('left'));
        if (jokesCarusel.is(":animated")) return false;
        $(this).parent().find('a.btn_prev').show();
        if (carusLeft > maxLeft-liWidth || carusLeft == 0  || carusLeft == -liWidth) {
            if (jokesCarusel.find('li:last').children().length == 0) {
                $.post(_LANG_URL + block.url + (countLi - 1) + '/', {}, function(data){
                    jokesCarusel.find('li:last').replaceWith(data);
                    countLi = jokesCarusel.find('li').size();
                    jokesCarusel.width(liWidth*countLi);
                    if (carusLeft == maxLeft) {
                        $(this).hide();
                    }
                });
            }
            jokesCarusel.animate({left: '-='+liWidth*block.li_per_time}, 'slow');
        } else if (maxLeft - carusLeft == 2*liWidth) {
            jokesCarusel.animate({left: '-='+liWidth}, 'slow');
            $(this).hide();
        };
        return false;
    });

    $('#'+block.id+' .btn_prev').live('click',function(){
        var jokesCarusel = $(this).parent().parent().find('.carousel_container ul');
			carusLeft = parseInt(jokesCarusel.css('left'));
        	liWidth = block.li_width;
        if (jokesCarusel.is(":animated")) return false;
		$(this).parent().find('a.btn_next').show();
        if (carusLeft == -liWidth) {
            jokesCarusel.animate({left: '+='+liWidth}, 'slow');
			$(this).hide();
        } else if (carusLeft < 0 || jokesCarusel.find('li:first').children().length == 0) {
            jokesCarusel.animate({left: '+='+liWidth*block.li_per_time}, 'slow');
            if (carusLeft == -liWidth*block.li_per_time) {
                $(this).hide();
            }
        };
        return false;
    });	
}

var showAllTopnewsImages = function(){
	var block = $('div.NewFeaturedNews');
	if (block.find('div.TabContent:eq(1)').find('a img').attr('src') == ''){
		block.find('div.TabContent').each(function(i){
			$(this).find('a img').attr('src', topnewsImages[i]);
		});	
	}
}

var cssFix = function(){

  var u = navigator.userAgent.toLowerCase(),

  is = function(t){return (u.indexOf(t)!=-1)};

  $("html").addClass([

    (!(/opera|webtv/i.test(u))&&/msie (\d)/.test(u))?('ie ie'+RegExp.$1)

      :is('firefox/2')?'gecko ff2'

      :is('firefox/3')?'gecko ff3'

      :is('gecko/')?'gecko'

      :is('opera/9')?'opera opera9':/opera (\d)/.test(u)?'opera opera'+RegExp.$1

      :is('konqueror')?'konqueror'

      :is('applewebkit/')?'webkit safari'

      :is('mozilla/')?'gecko':'',

    (is('x11')||is('linux'))?' linux'

      :is('mac')?' mac'

      :is('win')?' win':''

  ].join(''));

}();

function dump(event)
{
    var newResult = '{ ';
    for (var prop in event )
    newResult += prop + ': ' + event[prop] + ', ';
    newResult = newResult.substr(0, newResult.length - 2) + ' }';

    alert(newResult);
}

String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g, '');
}

function validate_email(str){
	var email_regular = new RegExp(/^([a-z0-9_\-\.]+)@[a-z0-9\-]+(\.[a-z0-9\-]+)*(\.[a-z]{2,3})$/i);
	return email_regular.test(str);
}

function validate_tel(str){
	var tel_regular = new RegExp(/^(\+?[0-9]{10,})$/i);
	return tel_regular.test(str);
}

var ProfileAuthtorizeOpenWindows = 0;

/* this is content from jquery.popupwin.js. it needed for popup login */
(function($){
	$.fn.popupWin = function(options){
		
		var $self=$(this);
		var def = {
				'title'		:	"Popup",
				'close'		:	"X",
				'content'	:	"Hello",
				'type'		:	"",
				'opacity'	:	"true",
				'plugins'	:	""
			};
		var opt=$.extend(def,options);
		$(this).click(function(){
			opt.isMail = false;
			if ($(this).hasClass('mail')) {
				opt.returnUrl = $(this).attr('href');
				opt.isMail = true;
			}
			
			$(this).buildPopup(opt);
			return false;
		});
	};
	$.fn.extend({
		buildPopup:	function(opt){
			if (0 < ProfileAuthtorizeOpenWindows) return false;
			if (opt.test == 1) return false;
			
			var cl = opt.opacity == "true" ? "popupWin" : "popupWin smallWin";
			var $p = $("<div class="+cl+">&nbsp;</div>").appendTo("body");
			if (opt.opacity == "true") {
				$('<div class="o">&nbsp;</div>').css("height", $(document).height()).prependTo($p);
			}
			var $c = $('<div class="c">&nbsp;</div>').html('<h3 class="title">'+opt.title+'</h3>'+ (opt.type == 'message' ? '<div class="content"><div class="message">' + opt.content + '</div></div>' : '<div class="content">'+opt.content+'</div>')).appendTo($p);
			$('<a href="#" class="close">&nbsp;</a>').html(opt.close).appendTo($p.children().children("h3")).click(function(){
				$p.remove();
				ProfileAuthtorizeOpenWindows = 0;
				return false;
			});
			$p.find(".f .close").click(function(){
				$p.remove();
				ProfileAuthtorizeOpenWindows = 0;
				return false;
			});
			$('div.popupWin form input[name=nick]').focus();
			opt.returnUrlPreviousState = $('div.popupWin form input[name=return_url]').val();
			
			if (opt.isMail) {
				$('div.popupWin form input[name=return_url]').val(opt.returnUrl);
			} else {
				if (typeof(globalReturnUrl) != 'undefined'){
					$('div.popupWin form input[name=return_url]').val(globalReturnUrl);
				} else {
				  $('div.popupWin form input[name=return_url]').val(opt.returnUrlPreviousState);
				}				
			}
			
			if (opt.plugins) eval(opt.plugins);
			ProfileAuthtorizeOpenWindows++;
		}
	});
})(jQuery);

/*
* Function to increase count of video-views.
* DO NOT DELETE !
*/
function playsStarted(vid, video_title, category_name) {
	jQuery.get ('http://video.tochka.net/ajax/watched/'+vid+'/', {},
		function(data, status) {}, 
		'html'
	);
    if(vid == 219390) {
        jQuery.get ('http://ad.adriver.ru/cgi-bin/click.cgi?sid=1&ad=256631&bt=21&pid=529293&bid=993040&bn=993040&rnd=1153585711');
    }
	return false;
}

jQuery(document).ready(function() {
<!--
// -----------------------------------------------------------------------------
// Globals
// Major version of Flash required
var requiredMajorVersion = 8;
// Minor version of Flash required
var requiredMinorVersion = 0;
// Minor version of Flash required
var requiredRevision = 0;
// -----------------------------------------------------------------------------
// -->
//if(!document.getElementById('html5-player')){
    var hasReqestedVersion = DetectFlashVer(requiredMajorVersion, requiredMinorVersion, requiredRevision);
    var hasReqestedVersion_express_install = DetectFlashVer(10, 1, 0);
    if(!hasReqestedVersion) {
    	jQuery("#html5-player").show();
        jQuery("#html5-player").next('embed').hide();
        jQuery("#html5-player").next('object').hide();
    }else{
        if(!hasReqestedVersion_express_install){
            jQuery("#plr #single").hide();
            jQuery("#expr_install_obj").show();
        }
    }
//}

});

/*
 * Same as carousel(), but this version takes into consideration only the ul
 * elements that are children of .carousel_container; same with li elements,
 * so the carousel won't break when its elements in turn contain lists of
 * elements. It'll also return false early if the list has only one li element
 * (that is, nothing will happen when btn_next, btn_prev are clicked).
 */
var carouselV2 = function(block){
	$('#'+block.id+' .btn_next').live('click',function(){
		var carousel = $(this).parent().parent().find('.carousel_container > ul'),
			countLi = carousel.children('li').length,
			liWidth = block.li_width,
			maxLeft = (countLi-1*block.li_in_row)*-liWidth,
			carusLeft = carousel.css('left') == 'auto' ? 0 : parseInt(carousel.css('left'));

		if (countLi == 1 || carousel.is(':animated')) return false;
		if (carusLeft > maxLeft || (carusLeft == 0 && countLi != 1) || (carusLeft == -liWidth*block.li_in_row && countLi != 2)) {
			carousel.animate({left: '-='+liWidth*block.li_in_row}, 'slow');

			if(block.counter_id) {
                $('#'+block.counter_id).text(parseInt($('#'+block.counter_id).text())+1);
            }

            if(block.notCyclic) {
                $(this).hide();
                $(this).parent().find('.btn_prev').show();
            }

			$(this).parent().find('a.notAble').removeClass('notAble');
		} else if (carusLeft < maxLeft) {
			carousel.animate({left: '-='+liWidth*block.li_in_row}, 'slow');

			$(this).addClass('notAble');
		} else if(!block.notCyclic) {
            var temp = carousel.html();

			carousel
				.width(carousel.width()*2)
				.append(temp)
				.animate({left: '-='+liWidth*block.li_in_row}, 'slow', '', function(){
					carousel
						.width(carousel.width()/2)
						.css('left', '0px')
						.children('li:lt('+countLi+')').remove();
				});
                
            if(block.counter_id) {
                $('#'+block.counter_id).text(1);
            }
		}
		if (typeof(block.function_next) == 'function'){
			(block.function_next)();
		}
		return false;
	});
	$('#'+block.id+' .btn_prev').live('click',function(){
		var carousel = $(this).parent().parent().find('.carousel_container > ul'),
			countLi = carousel.children('li').length,
			carusLeft = carousel.css('left') == 'auto' ? 0 :parseInt(carousel.css('left')),
			liWidth = block.li_width;
            
		if (countLi == 1 || carousel.is(':animated')) return false;
		if (carusLeft == -liWidth*block.li_in_row) {
			carousel.animate({left: '+='+liWidth*block.li_in_row}, 'slow');

			if(block.counter_id) {
                $('#'+block.counter_id).text(parseInt($('#'+block.counter_id).text())-1);
            }

            if(block.notCyclic) {
                $(this).hide();
                $(this).parent().find('.btn_next').show();
            }

			$(this).addClass('notAble');
		} else if (carusLeft < 0 || carousel.find('li:first').children().length == 0) {
			carousel.animate({left: '+='+liWidth*block.li_in_row}, 'slow');

            if(block.counter_id) {
                $('#'+block.counter_id).text(parseInt($('#'+block.counter_id).text())-1);
            }

			$(this).parent().find('a.notAble').removeClass('notAble');
			if (carusLeft == -liWidth) {
				$(this).addClass('notAble');
			}
		} else if(!block.notCyclic) {
            var temp = carousel.html();

			carousel
				.width(carousel.width()*2)
				.prepend(temp)
				.css('left', liWidth*(-countLi)+'px')
				.animate({left: '+='+liWidth*block.li_in_row}, 'slow', '', function(){
					carousel
						.width(carousel.width()/2)
						.children('li:gt('+(countLi-1)+')').remove();
				});
			$('#'+block.counter_id).text(countLi/block.li_in_row);
		}
		if (typeof(block.function_prev) == 'function'){
			(block.function_prev)();
		}
		return false;
	});
};

/* 
 * Calculating links count in soc-networks
 *      callback = function (url, result) {}
 *         result = {vk: 0, fb: 0, tw: 0, sum: 0}
 *      callbackStep = function (url, soc, count) {}
 *         soc = vk | fb | tw 
 */
var socLinkData = {};
function calculateSocLinkTotal(linkUrl, callback, callbackStep) {
    if (socLinkData[linkUrl] != undefined)
        return false;
    socLinkData[linkUrl] = {vk: null, fb: null, tw: null, sum: 0, callback: callback, callbackStep: callbackStep};
    calculateLinkVk(linkUrl);
    calculateLinkFb(linkUrl);
    calculateLinkTw(linkUrl);
}
function calculateSocLinkCallback(linkUrl) {
    if ((socLinkData[linkUrl].vk != null) && (socLinkData[linkUrl].fb != null) && (socLinkData[linkUrl].tw != null)) {
        socLinkData[linkUrl].sum = socLinkData[linkUrl].vk + socLinkData[linkUrl].fb + socLinkData[linkUrl].tw;
        delete socLinkData[linkUrl].callbackStep;
        var callback = socLinkData[linkUrl].callback;
        delete socLinkData[linkUrl].callback;
        var result = socLinkData[linkUrl];
        delete socLinkData[linkUrl];
        callback(linkUrl, result);
    }
}
var vkIndexRefUrl = [];
function calculateLinkVk(linkUrl) {
    if (typeof(VK) == 'undefined')
        VK = {}
    vkIndexRefUrl.push(linkUrl);
    VK.Share = {}
    VK.Share.count = function(index, count) {
        socLinkData[vkIndexRefUrl[index - 1]].vk = parseInt(count);
        if (socLinkData[vkIndexRefUrl[index - 1]].callbackStep != null)
            socLinkData[vkIndexRefUrl[index - 1]].callbackStep(vkIndexRefUrl[index - 1], 'vk', socLinkData[vkIndexRefUrl[index - 1]].vk);
        calculateSocLinkCallback(vkIndexRefUrl[index - 1]);
    }
    $.getJSON('http://vkontakte.ru/share.php?act=count&index=' + vkIndexRefUrl.length + '&url=' + linkUrl + '&format=json&callback=?');
}
function calculateLinkFb(linkUrl) {
    $.getJSON('https://api.facebook.com/method/fql.query?query=select total_count, url from link_stat where url="' +linkUrl  + '"&format=json&callback=?',
        function(data) {
            socLinkData[data[0].url].fb = parseInt(data[0]['total_count']);
            if (socLinkData[data[0].url].callbackStep != null)
                socLinkData[data[0].url].callbackStep(data[0].url, 'fb', socLinkData[data[0].url].fb);
            calculateSocLinkCallback(data[0].url);
        }
    );
}
function calculateLinkTw(linkUrl) {
    $.getJSON('http://urls.api.twitter.com/1/urls/count.json?url=' + linkUrl + '&callback=?',
        function(data) {
            socLinkData[data.url].tw = parseInt(data.count);
            if (socLinkData[data.url].callbackStep != null)
                socLinkData[data.url].callbackStep(data.url, 'tw', socLinkData[data.url].tw);
            calculateSocLinkCallback(data.url);
        }
    );
}
/*
 * End calculating soc-links
 */

