/* Author:

*/
$(function() {
	if ($.browser.msie && $.browser.version < 9) {
		$('.colimg + .coltxt').addClass('iefixcoltxt');
		$('.coltxt + .colimg').addClass('iefixcolimg');
		$('.colimg + .aboutwork').addClass('iefixaboutwork');
	}

    $("#kultural .any_table__cell a").click(function(){
        var link = $(this).attr('href');
        $.colorbox({
            href:link,
            iframe: false,
            width: 720,
            onComplete: function(){
                $('#cboxTitle').hide();
            }
        });
        return false;
    });
    
	$('.sitesearch').inputoverlabel();

	$('.rubricWrap').each(function(){
		var rubricWrap = $(this);
		var rubricList = rubricWrap.find('.rubricList');
		var t = 350, e = 'easeOutQuad';
		rubricList.slideUp(t, e, function(){rubricWrap.removeClass('show')});
		$(this).find('.door').click(function(){
			if (!rubricWrap.hasClass('show')) {
				rubricList.slideDown(t, e, function(){rubricWrap.addClass('show')});
			} else {
				rubricList.slideUp(t, e, function(){rubricWrap.removeClass('show')});
			}
		});
		rubricList.find('.close').click(function(){
			rubricList.slideUp(t, e, function(){rubricWrap.removeClass('show')});
		});
	});


	$('.menu').each(function(){
		var menu = $(this);
		var ul = menu.find('ul');
		var t = 250, eff = 'swing';
		ul.css('display','block');
		ul.each(function(i){
			var m = $(this);
			m.css({display: 'none'});
			var LI = m.parent('li');
			LI.children('a').click(function(e){
			        e.preventDefault();
				if (!LI.hasClass('open')) {
					LI.addClass('open');
					m.slideDown(t, eff, function(){
						LI.addClass('open');
					});
				} else {
//					if (!LI.data('current')) {
						m.slideUp(t, eff, function(){
							LI.removeClass('open');
						});
//					}
				}
			});
			if (i==ul.length-1) {
				var curr = menu.find('.current:last()');
				if (curr.length > 0) {
					curr.data('current',true).addClass('open');
					curr.parents('li').addClass('open current').data('current',true);
					curr.parents('ul').css('display','block');
				}
			}
			//menu.find('.current.open > a').click (function () {
	        	//        return false;
        		//});
		});
       		var current_item = menu.find('.current.open > a:last-child').attr('href');
       		var current_url = 'http://'+document.location.host+current_item;
       		var current_href = document.location.href;
       		if(current_href != current_url) {
       		        var current_link = menu.find('.current.open > a:last-child');                                
       		        current_link.parent().removeClass('open');
       		        current_link.css({'color':'#000','cursor':'pointer'});
               		current_link.click (function () {
               		        document.location.href = current_url;
       		        });
       		};
	});


	$('.e_menu').each(function(){
		var menu = $(this);
		var ul = menu.find('ul');
		var t = 350, eff = 'easeOutQuad';
		ul.css('display','block');
		ul.slideUp(function(){
			var m = $(this);
			var LI = m.parent('li');
			var opener = $('<span class="structure__close"><i class="e_toggle">+</i></span>').appendTo(LI.children('.structure__item_in,.sub_structure__item_in'));
			LI.addClass('it_close');
			opener.find('.e_toggle').click(function(e){
			        e.preventDefault();
			        var lnk = $(this);
				if (!lnk.hasClass('open')) {
					LI.removeClass('it_close').addClass('it_open');
					m.slideDown(t, eff, function(){
						lnk.addClass('open').text('-');
						LI.removeClass('it_close').addClass('it_open');
						if ($.browser.msie && $.browser.version < 8) {
							$('.footer').css('display','none');
							window.setTimeout(function() {
								$('.footer').css('display','block');
							}, 100);
						}
					});
				} else {
					LI.removeClass('it_open').addClass('it_close');
					m.slideUp(t, eff, function(){
						lnk.removeClass('open').text('+');
						LI.removeClass('it_open').addClass('it_close');
						if ($.browser.msie && $.browser.version < 8) {
							$('.footer').css('display','none');
							window.setTimeout(function() {
								$('.footer').css('display','block');
							}, 100);
						}
					});
				}
			});
		});
	});


  /* @todo если не нужно, убрать. переделал под colorbox (juliv)
	$('.openinpopup').each(function(){
		var a = $(this);
		a.append('<em class="zoom" />');
		var img = a.find('img');
		a.addClass(img.attr('class'));
                img.attr('class','');
               	var bigimg = a.find('.bigimg');
               	if (bigimg.length < 1) {
               		a.append('<div class="bigimg"><img src="'+a.attr('href')+'" alt="" /></div>');
                	bigimg = a.find('.bigimg');
                }
                a.click(function(){
			bigimg.dialog({
				modal: true,
				open: function(event, ui) {
					var obj = $(this);
					obj.dialog('option', 'width', obj.find('img').width());
					obj.dialog('option', 'height', obj.find('img').height());
					obj.dialog('option', 'position', 'center');
					$('.ui-widget-overlay').unbind('click.dclose').bind('click.dclose', function(){
						obj.dialog('close');
					});
				},
				resizable: false
			});
                	return false;
		});
	});
	*/


  // Colorbox for history images
  $('a.history_photo__item').colorbox();

  // ColorBox for popup of event in day
  //var calend_month = $('div.calend-month');
  $('span.event-day[data-eid], li.cep-li[data-eid]').colorbox({
    href:function(){return '#eid-'+$(this).attr('data-eid')},
    inline:true,
    title:false,
    initialWidth:function(){return parseInt($('div.calend-month').width() * 0.9)},
    initialHeight:100,
    width:function(){return parseInt($('div.calend-month').width() * 0.9)},
    left:function(){return parseInt($('div.calend-month').offset().left - $(window).scrollLeft() - 10 + $('div.calend-month').width() * 0.05)},
    top:function(){return parseInt($('div.calend-month').offset().top - $(window).scrollTop() + 100)},
    className:'colorbox-cep'
  });




	
	$('.filterform .calend').each(function(){
		var inp = $(this);
		inp.datepicker({
		dayNamesMin:['Вс','Пн','Вт','Ср','Чт','Пт','Сб'],
		dayNames:['Воскресенье','Понедельник','Вторник','Среда','Четверг','Пятница','Суббота'],
		monthNames:['Январь','Февраль','Март','Апрель','Май','Июнь','Июль','Август','Сентябрь','Октябрь','Ноябрь','Декабрь'],
		firstDay : 1,
		dateFormat: 'dd.mm.yy'}).mask('99.99.9999');
		$('<em class="cal"></em>').insertAfter(inp).click(function(e){
			inp.focus();
		});
	});


	$('.socialtabs').tabs();


/* open and close project square in Metro design*/	
	$('a.projectlist_item.parent').click(function(){
		$(this).next('.proj_in').toggle('fast');
		return false;
	});
	
	
	
	$('.search_cat_filter, .mapcontextmenu').each(function(){
		var filterbox = $(this);
		filterbox.find('input').each(function(){
			var inp = $(this); var label = filterbox.find('label[for='+inp.attr('id')+']');
			inp.addClass('invisible');
			if (inp.is(':checked')) label.addClass('checked');
			inp.change(function(){
				filterbox.find('input').each(function(){
					var inp = $(this); var label = filterbox.find('label[for='+inp.attr('id')+']');
					if (inp.is(':checked')) label.addClass('checked'); else label.removeClass('checked');
				});
			});
		});
	});


	articleShare();

	answerOpen ();
	blindCur ();
	textErrorObserver(); // сканнер Ctrl+Enter

	$('.subordinate .areafilter .filterblock').each(function(){
		var filterblock = $(this);
		filterblock.data('zindex',1);
		var fcontent = $(this).find('.fcontent');
		filterblock.find('.ftitle a').toggle(function(){
			var zindex = filterblock.data('zindex') + 1;
			filterblock.css('z-index',zindex);
			filterblock.addClass('current'); fcontent.stop().slideDown(600, 'easeOutBack');
			$('.subordinate .areafilter .filterblock').data('zindex', zindex);
		}, function(){
			fcontent.stop().slideUp(600, 'easeOutQuad', function(){
				filterblock.removeClass('current'); 
			}); 
		});

		filterblock.click(function(){
			var zindex = filterblock.data('zindex') + 1;
			filterblock.css('z-index',zindex);
			$('.subordinate .areafilter .filterblock').data('zindex', zindex);
		});
	});

	$('.subordinate_cat_list').each(function(){
		$(this).find('li ul').each(function(){
			var ul = $(this);
			var LI = $(this).parent('li');
			ul.css('display','none');
			LI.addClass('ico_plus');
			LI.toggle(function(){
				ul.stop().slideDown(600, 'easeOutQuad', function(){
					LI.removeClass('ico_plus').addClass('ico_minus');
				});
			},function(){
				ul.stop().slideUp(600, 'easeOutQuad', function(){
					LI.removeClass('ico_minus').addClass('ico_plus');
				}); 
			});
			LI.find('li a').click(function(e){
				e.stopImmediatePropagation();
			});
		});
	});

	$('#linkListfot').each(function(){
		var carousel = $(this);
		var tmr;
		var li = carousel.find('LI'), licnt  = li.length;
		carousel.jcarousel({
			initCallback: function(){
				var crsl = this, jcarouselcontainer = carousel.parents('.jcarousel-clip:eq(0)'), maincarousel = jcarouselcontainer.parents('.jcarousel-container:eq(0)');
				carousel.css({'margin-left':'auto', 'margin-right':'auto'});
				crsl.wrap = null; crsl.visible = null; crsl.scroll = 3;
				var LI = carousel.parents('LI');
				var W = 0, full = LI.find('.full'), nawwrap = maincarousel.find('.jcarousel-prev, .jcarousel-next').wrapAll('<div class="nawwrap" />');
				li.each(function(){
					W += $(this).outerWidth(true);
				});
				var oW = W/licnt;
				jcarouselcontainer.css('max-width','9999em');
				var cnt = Math.floor((jcarouselcontainer.width()+parseInt(li.css('margin-right'), 10)) / oW);
				var scr = (cnt > 3) ? 3 : cnt-1;
				crsl.scroll = (scr > 0) ? scr : 1;
				crsl.visible = cnt;
				crsl.offset = 1; crsl.start = 1;
				jcarouselcontainer.css({'max-width': cnt * oW , 'margin-left':'auto', 'margin-right':'auto' });
				nawwrap.css('display',(cnt >= licnt) ? 'none':'block');
				crsl.wrap = (cnt >= licnt)? null : 'circular';
/*
				$(window).resize(function(){
					window.clearTimeout(tmr);
					tmr = window.setTimeout(function(){
						window.clearTimeout(tmr);
//						alert(crsl.toSource())
//						crsl.jcarousel.reset();
//						crsl.initCallback(crsl,'reset');
					}, 10);
				});
*/
				
			},
			reloadCallback: function(){
				this.initCallback(this,'reset');
			},
			itemFirstInCallback: function(a, b, c, d) {
				if (typeof window['inTemplateCalbackFunction'] == 'function') 
					inTemplateCalbackFunction(a, b, c, d);
			}
		});
	});


	$('.photo-slideshow__wrapper').each(function(i){
		var cont = $(this), id='photo-slideshow_'+i;
		cont.attr('id', id);

		$("#"+id+" a.thumb-colorbox").attr('rel', 'gal['+i+']');
		$("#"+id+" a.thumb-colorbox").colorbox({
			rel: 'gal['+i+']',
			title: function(){
				return $(this).parent().find('.caption').html();
			},
			cbox_load: function(){
			},
			className:'colorbox-gallery'
		});
	
		$("#"+id+" .photo-gallery__zoom").click(function(){
			$("#"+id+" a.thumb-colorbox").eq($(this).attr('data-image')).click();
		});

		// Выносим опции Galleriffic
		var opts = {
			delay:                     100,
			numThumbs:                 8,
			preloadAhead:              10,
			enableTopPager:            false,
			enableBottomPager:         true,
			maxPagesToShow:            1,
			imageContainerSel:         '#'+id+' .photo-gallery__slideshow',
			controlsContainerSel:      '#'+id+' .photo-gallery__controls',
			captionContainerSel:       '#'+id+' .photo-gallery__caption',
			loadingContainerSel:       '#'+id+' .photo-gallery__loading',
			renderSSControls:          true,
			renderNavControls:         true,
			playLinkText:              '',
			pauseLinkText:             '',
			prevLinkText:              '',
			nextLinkText:              '',
			nextPageLinkText:          'следующая страница',
			prevPageLinkText:          'предыдущая страница',
			enableHistory:             false,
			enableKeyboardNavigation:  false,
			autoStart:                 false,
			syncTransitions:           false,
			defaultTransitionDuration: 500,
			onSlideChange:             function(prevIndex, nextIndex) {
				$("#"+id+" .photo-gallery__zoom").attr('data-image', nextIndex);
			}
		};

		// Раздел media
		if ($(this).hasClass('__media')) {
			opts.enableBottomPager = false;
		}

		// Initialize Advanced Galleriffic Gallery
		var gallery = $("#"+id+" .photo-gallery__navigation").galleriffic(opts);

/*
*/	
	}); // $('.photo-slideshow__wrapper').each

/*
  // Colorbox on Galleriffic Gallery thumbs
  $("#photo-gallery__thumbs a.thumb-colorbox").colorbox({
    title: function(){
      return $(this).parent().find('.caption').html();
    },
    className:'colorbox-gallery'
  });
  $('.photo-gallery__zoom').click(function(){
    var id = $(this).attr('data-image');
    $('#photo-gallery__thumbs a.thumb-colorbox').eq(id).click();
  });

  // Initialize Advanced Galleriffic Gallery
  var gallery = $('#photo-gallery__thumbs').galleriffic({
    delay:                     100,
    numThumbs:                 80,
    preloadAhead:              10,
    enableTopPager:            false,
    enableBottomPager:         false,
    maxPagesToShow:            1,
    imageContainerSel:         '#photo-gallery__slideshow',
    controlsContainerSel:      '#photo-gallery__controls',
    captionContainerSel:       '#photo-gallery__caption',
    loadingContainerSel:       '#photo-gallery__loading',
    renderSSControls:          false,
    renderNavControls:         true,
    playLinkText:              '',
    pauseLinkText:             '',
    prevLinkText:              '',
    nextLinkText:              '',
    nextPageLinkText:          '',
    prevPageLinkText:          '',
    enableHistory:             false,
    enableKeyboardNavigation:  false,
    autoStart:                 false,
    syncTransitions:           true,
    defaultTransitionDuration: 500,
    onSlideChange:             function(prevIndex, nextIndex) {
      $('.photo-gallery__zoom').attr('data-image', nextIndex);
    }
  });
*/

  // Переключатель табов в соц. блоке (juliv)
  var tabComboContainers = $('.social-block dd'),
      tabComboNav = $('.social-block__dt');
  tabComboNav.click(function () {
    if ($(this).hasClass('active')) return;
    var index = tabComboNav.index(this);
    //var hash = $(this).attr('data-tab');
    tabComboContainers.hide().removeClass('active').eq(index).addClass('active').fadeIn('fast');
    tabComboNav.removeClass('active');
    $(this).addClass('active');
	if(($(this).data('soctype') == "vk") && (typeof vk_init == "function"))
		vk_init();
	if(($(this).data('soctype') == "tw") && (typeof twi_init == "function"))
		twi_init();
    return false;
  });
  if($('.social-block__vk').hasClass('active')){
  	vk_init();
  }
  if($('.social-block__tw').hasClass('active')){
  	twi_init();
  }





  /* заглушка для видео и презентаций при печати*/
  
  $('.primary_content iframe, .slideWrap, .player').after('<div class="replace_img">Медиаконтент</div>');
  
  
  
  /**/

  $('.news_filter').enwide({
	itemClass: 'news_filter__item'
  });
  $('.js-customSelect').selectik({
  	maxItems: 7
  });


}); // DOM loaded


(function($) {

	$.fn.enwide = function(options) {
		return this.each(function() {

			var cont = $(this),
				w = cont.width(),
				i = 0,
				el = $('.' + options.itemClass, cont),
				arr = [];

			arr[i] = [];
			el.each(function() {
				var that = $(this);
				arr[i].push(that);
				if (that.next().length > 0 && that.offset().top < that.next().offset().top) {
					that.addClass('line-last');
					i += 1;
					arr[i] = [];
				}
			});

			for (i = 0; i < arr.length; i += 1) {
				alignLine(i);
			}

			function alignLine(num) {

				var elW = 0;
				for (var n = 0; n < arr[num].length; n += 1) {
					elW += arr[num][n].width();
				}

				var amp = w - elW,
					pad = (w - elW) / 2 / arr[num].length,
					pad = Math.floor(pad),
					reminds = (w - elW) - pad * 2 *  arr[num].length,
					reminds = Math.floor(reminds) - 2;

				for (var n = 0; n < arr[num].length; n += 1) {
					arr[num][n].find('a').css({
						'padding-left': pad,
						'padding-right': pad
					});
					if (arr[num].length - n === 2) {
						arr[num][n].find('a').css({
							'padding-right': pad + reminds
						});
					}
				}
				
			};

		});
	};

})(jQuery);




function articleShare(){
	$('.article_share .copylink').each(function(){
		var copylink = $(this);
		var lnk = copylink.find('a');
		var par = copylink.parent('.article_share__gist');
		par.addClass('show');
		var clip = new ZeroClipboard.Client();
		clip.setText(par.find('textarea,input:text').val());
		ZeroClipboard.setMoviePath('/bitrix/templates/trp3_main_d3/swf/ZeroClipboard.swf');
		clip.glue(lnk.attr('id'), copylink.attr('id'));
		clip.addEventListener('onComplete', function(){ alert('Код скопирован в буфер.'); });
		par.removeClass('show');
	});
}

// Расположение окна события относительно календаря
function colorbox_eventday_resize() {
  if ($('div.colorbox-cep:visible').size() == 1) {
    //console.log($.colorbox.settings.left +' *** '+ $.colorbox.settings.top);
    var calend_month = $('div.calend-month');
    $.colorbox.setPosition(parseInt(calend_month.offset().left - $(window).scrollLeft() - 10 + calend_month.width() * 0.05), parseInt(calend_month.offset().top - $(window).scrollTop() + 100));
  }
}


(function($) { //create closure
$.fn.notacarousel = function(options){
	var defaults = {
		toLeftTmpl: '<a href="javascript:void(0);"><span></span></a>',
		toRightTmpl: '<a href="javascript:void(0);"><span></span></a>',
		notArrows: false, //показывать стрелки перехода между картинками или нет
		wrap: 'circular',
		start: 1,
		width: false, // ширина контейнера
		height: false, // высота контейнера
		selector: '.slide',
		scroll: 1,
		vertical: false,
		easing: 'easeInQuad',
		animation: 300,
		preview: false, // true - галерея превьюшек с увеличением; false - обыкновенная карусель
		enlargeto: false, // например '<iframe src="" width="370" height="310" frameborder="0" marginwidth="0" marginheight="0" scrolling="no" style="" allowfullscreen webkitallowfullscreen mozallowfullscreen></iframe>'
		enlargeattr: false, // например 'src' от iframe
		enlargefrom: false, // например 'a.href' - в src iframe взять значение атрибута 'href' ссылки 'a'
		enlargeclass: false, // например '.class' - брать не весь html, а конкретный класс.
		itemFallbackDimension: null,
		//component_path:null
	};
	var errors = 0; var msg='';
	var o = $.extend(defaults, options);
	var ul = $(this);

	ul.jcarousel({
		buttonNextHTML: o.toRightTmpl,
		buttonPrevHTML: o.toLeftTmpl,
		wrap: o.wrap,
		start: o.start,
		easing: o.easing,
		scroll: o.scroll,
		vertical: o.vertical,
		animation: o.animation,
		itemFallbackDimension: o.itemFallbackDimension,
		initCallback: carouselPrepare,
		animationStepCallback: carouselNextStep,
		itemVisibleInCallback: {
			onBeforeAnimation: onBeforeAnimationStep,
			onAfterAnimation: onAfterAnimationStep
		}
	});

	function carouselPrepare(carousel) {
		if($(o.selector).length==1){ // убираем карусель превьюшек если картинка одна.
			$(".jcarousel-clip-horizontal").css({"display":"none"});
		}
		var id = carousel.container.context.id, txt = '';
		carousel.container.find(o.selector).each(function(i){
			txt += '<li><a href="#">'+(i+1)+'</a></li>';
		});
		carousel.container.append('<ul id="'+id+'control" class="carouselcontrol">'+txt+'</ul>');
		$('#'+id+'control a').bind('click', function() {
			$('#'+id+'control').find('.current').removeClass('current');
	                carousel.scroll($.jcarousel.intval($(this).text()));
	                $(this).parent().addClass('current');
			return false;
		});
		carousel.container.css({ overflow: 'hidden' });
		if (o.width) carousel.container.width(o.width);
		if (o.height) carousel.container.height(o.height);
		if (o.preview) {
			if(o.notArrows == false){
				carousel.container.prepend('<div class="enlargefoto" id="'+id+'enlarge"></div><div class="slidenav"><a href="javascript:void(0)" class="nav toleft"><span>&laquo;</span></a><a href="javascript:void(0)" class="nav toright"><span>&raquo;</span></a></div>');
			}else{
				carousel.container.prepend('<div class="enlargefoto" id="'+id+'enlarge"></div><div class="slidenav"></div>');
			}
			var li = carousel.container.find(o.selector);
			var cnt = li.length;
			$(document).on('click', '#'+ id+ ' '+o.selector, function(e){
			    e.preventDefault();
				var enlargefoto = $('#'+id+'enlarge');
				var olds = enlargefoto.find('.enlslide');
				if(o.enlargeclass){
					var newhtml = (!o.enlargeto) ? $(this).find(o.enlargeclass).html() : o.enlargeto;
				}else{
					var newhtml = (!o.enlargeto) ? $(this).html() : o.enlargeto;
				}

				if(o.enlargefrom=="a.href"){ // for slideshare
					var fr = o.enlargefrom.split('.');
					url=$(this).find(fr[0]).attr(fr[1]);
					current_element=$(this);
					slide_url=url.split('/');
					slideshow_id=slide_url[slide_url.length-1];
					$.ajax({
						url:o.component_path,
						method: "GET",
						dataType:"json",
						data:{id:slideshow_id},
						success: function(header){
							if(header.Status!="200 OK"){
								url=o.fail_cap; // картинка заглушки, в случае фейла
							}
							var full_image = $(newhtml).data("main");
							var news = $('<div class="enlslide">'+newhtml+'</div>');
							if (o.enlargeto && o.enlargeattr && o.enlargefrom) {
								news.find('*['+o.enlargeattr+']').attr(o.enlargeattr,url);
							}
							news.find("img").attr("src",full_image);
							olds.css('zIndex',0).animate({opacity:0}, 600, function(){ olds.detach(); });
							news.css({opacity:0,'zIndex':1}).appendTo(enlargefoto).animate({opacity:1}, 600, function(){});
							carousel.container.find(o.selector+'.current').removeClass('current');
							$(current_element).addClass('current');
						}
					});
				}
				if(o.enlargefrom=="img.src"){
					current_element=$(this);
					var full_image = $(newhtml).data("main");
					var news = $('<div class="enlslide">'+newhtml+'</div>');
					if (o.enlargeto && o.enlargeattr && o.enlargefrom) {
						news.find('*['+o.enlargeattr+']').attr(o.enlargeattr,url);
					}
					news.find("img").attr("src",full_image);
					olds.css('zIndex',0).animate({opacity:0}, 600, function(){ olds.detach(); });
					news.css({opacity:0,'zIndex':1}).appendTo(enlargefoto).animate({opacity:1}, 600, function(){});
					carousel.container.find(o.selector+'.current').removeClass('current');
					$(current_element).addClass('current');
				}
			});
			li.each(function(i){
				var cont = $(this);
				cont.append('<strong class="slideinfo">'+(i+1)+'/'+(cnt)+'</strong>');
				if (i==0) cont.click();
			});
			carousel.container.find('.slidenav a').click(function(){
				var curr = carousel.container.find(o.selector+'.current');
				var ind = curr.attr('jcarouselindex');
				if ($(this).hasClass('toright')) {
					if (ind >= carousel.last) {
						carousel.container.find('.jcarousel-next').click();
					}
					curr.next().click();
				} else {
					if ((ind-1) <= carousel.first) {
						carousel.container.find('.jcarousel-prev').click();
					}
					curr.prev().click();
				}
				return false;
			});
		}
	}
	function carouselNextStep() {
	}
	function onBeforeAnimationStep(){

	}
	function onAfterAnimationStep(carousel){
		var n = carousel.first % carousel.options.size, id = carousel.container.context.id;
		n = (n <= 0)? carousel.options.size + n : n;
		$('#'+id+'control').find('.current').removeClass('current');
		$('#'+id+'control').find('li:eq('+(n-1)+')').addClass('current');
		var nextimg = carousel.container.find('.jcarousel-next .preview');
		var previmg = carousel.container.find('.jcarousel-prev .preview');
		if (nextimg.length > 0 && previmg.length > 0) { // картинки превьюшки около стрелок навигации
			previmg.attr('src',carousel.container.find('.jcarousel-item-'+(((n-1)<1) ? carousel.options.size : (n-1))+' img').attr('src'));
			nextimg.attr('src',carousel.container.find('.jcarousel-item-'+(((n+1)>carousel.options.size) ? 1 : (n+1))+' img').attr('src'));
		}
	}
}
//end of closure
})(jQuery);




(function($) { //create closure
$.fn.mainmediagal = function(options){
	var defaults = {};
	var errors = 0; var msg='';
	var o = $.extend(defaults, options);
	var ul = $(this);
	
	if (ul.find('.block').length < 4) {
		ul.jcarousel({
			vertical: true, 
			scroll: 1,
			itemFallbackDimension:81,
			initCallback: function(carousel){
				carousel.container.addClass('nocarouselnav');
			}
		});
	} else {
		ul.jcarousel({
		vertical: true, 
		wrap: 'circular', 
		scroll: 2,
		itemFallbackDimension:81
	});
	}
	ul.find('.block a').click(function(){
		if ($(this).parent().hasClass('current')) return false;
		var loader = $('#mainmediagalloader');
		if (loader.length < 1) { // start loader
			loader = $('<div id="mainmediagalloader"><img src="./i/ajax-loader.gif" /></div>');
			loader.css({position: 'absolute', top: '50%', left: '50%', width: '128px', height: '15px', margin: '-8px 0 0 -114px'}).appendTo(ul.parents('.mainmediagal'));
		}
		loader.show();$('#selectedcarousel').html('');
		ul.find('.current').removeClass('current');
		$(this).parent().addClass('current');

	//	$.get($(this).attr('href'), function(data) {
			var data = testgal, n = Date.now(), html = '<ul id="mainmediacar'+n+'" class="mainmediahorizontal">', galtitle;
			$.each(data, function(){
				if (this.galtitle) {
					galtitle = this.galtitle;
				} else {
//					html += '<li><img src="'+this.img+'" alt="" /><div class="slidetitle">'+this.title+'</div></li>';
					html += '<li><img src="'+this.img+'" alt="'+this.title+'" title="'+this.title+'" /></li>';
				}
			});
			html += '</ul>';
			$('#selectedcarousel').html(html);
			$('#mainmediacar'+n).jcarousel({
				scroll: 1,
				wrap: 'circular',
				animationStepCallback: function(){
					
				},
				initCallback: function(){
					var carousel = $('#mainmediacar'+n), cars = this;
					var clip = carousel.parents('.jcarousel-container:eq(0)');
					clip.append('<div class="nnum"><strong>'+(cars.offset%cars.size)+'</strong>/<span>'+cars.size+'</span></div>')
						.append('<div class="slidetitle">'+galtitle+'</div>');
					window.setTimeout(function(){loader.hide();},150); //hide loader
				}, 
				itemVisibleInCallback: { 
					onBeforeAnimation: function(instance, li, ind, state){
						var n = ind % instance.size();
						n = (n<1) ? instance.size() + n : n;
						if(state == "next" || state == "prev")
							instance.clip.parents('.jcarousel-container:eq(0)').find('.nnum strong').text(n);
					}
				}
				
			});
	//	}, "json");
		return false;
	});

	ul.find('.block a:eq(0)').click();
}
//end of closure
})(jQuery);



// =========================================

(function($) { //create closure
$.fn.horstructure = function(options){

	$(this).each(function(){
		var defaults = {
			t: null,
			toLeftTmpl: '<a href="javascript:void(0);"><span></span></a>',
			toRightTmpl: '<a href="javascript:void(0);"><span></span></a>',
			wrap: 'circular',
			start: 1,
			width: false, // ширина контейнера
			height: false, // высота контейнера
			selector: '.slide',
			scroll: 1,
			vertical: false,
			easing: 'easeInQuad',
			animation: 300,
			enlargeto: false, // например '<iframe src="" width="370" height="310" frameborder="0" marginwidth="0" marginheight="0" scrolling="no" style="" allowfullscreen webkitallowfullscreen mozallowfullscreen></iframe>'
			enlargeattr: false, // например 'src' от iframe
			enlargefrom: false // например 'a.href' - в src iframe взять значение атрибута 'href' ссылки 'a'
		};
		var errors = 0; var msg='';
		var o = $.extend(defaults, options);
		var menu = $(this), ul = menu.find('ul'), hortreecontainer = menu.parents('.hortreecontainer'), t = 150, eff = 'easeOutQuad';

		ul.each(function(){
			var m = $(this), LI = m.parent('li');
			m.css('display','none');
			LI.children('.htitem').wrap('<div class="htitemwrap" />');
			LI.addClass('is_child');
			var opener = $('<a href="#" class="opener">+</a>').appendTo(LI);
			LI.children('.htitemwrap').addClass('it_close');
			opener.click(function(e){
			        e.preventDefault();
			        var lnk = $(this);
				if (!lnk.hasClass('open')) {
					LI.children('.htitemwrap').removeClass('it_close');
			                    var strlog = "before: "+$(".jspPane").css('marginLeft')+"\n";
			                    m.slideDown({
			                        duration: t,
			                        easing: eff,
			                        step: function(now, fx) {
			                            var margin = parseInt($(".jspPane").css('marginLeft'));
			                            if(margin) {
//			                                console.log("rewrite margin on step "+now);
			                                $(".jspPane").css('marginLeft','');
			                            }
			                        },
			                        complete: function(){
			                            lnk.addClass('open').text('-');
			                            LI.children('.htitemwrap').removeClass('it_close');
			                            hortreecontainer.find('.jspContainer').height(menu.outerHeight(true));

			                            if ($.browser.msie && $.browser.version < 8) {
			                                $('.footer').css('display','none');
			                                window.setTimeout(function() {
			                                    $('.footer').css('display','block');
			                                }, 50);
			                            }
			                            window.clearTimeout(o.t);
			                            o.t = window.setTimeout(function(){ 
			                                sizerecalc(menu);
			                            }, 5);
			                        }
			                    });
				} else {
					LI.children('.htitemwrap').addClass('it_close');
					m.slideUp(t, eff, function(){
						lnk.removeClass('open').text('+');
						LI.children('.htitemwrap').addClass('it_close');
						hortreecontainer.find('.jspContainer').height(menu.outerHeight(true));

						if ($.browser.msie && $.browser.version < 8) {
							$('.footer').css('display','none');
							window.setTimeout(function() {
								$('.footer').css('display','block');
							}, 50);
						}
						window.clearTimeout(o.t);
						o.t = window.setTimeout(function(){ 
							sizerecalc(menu);
						}, 5);
					});
				}
			});
		});

		menu.children('LI').each(function(){
			var LI = $(this);
			var UL = LI.children('ul');
			if (UL.length > 0) {
				LI.children('.htitemwrap').removeClass('it_close');
				UL.css('display','block');
				LI.children('a').addClass('open').text('-');
				if ($.browser.msie && $.browser.version < 8) {
					$('.footer').css('display','none');
					window.setTimeout(function() {
						$('.footer').css('display','block');
					}, 50);
				}
				setwidth(menu);
			}
			LI.addClass('inlineblock');
		}); menu.addClass('parentinlineblock');

		sizerecalc(menu);
		hortreecontainer.addClass('scroll-pane horizontal-only');
//return false;
//		alert('')
		hortreecontainer.jScrollPane({
			showArrows: true,
			autoReinitialise: false
		});

//		window.clearTimeout(o.t);
		
		var rto; // resize timeout 
		$(window).bind('resize',function(){
			window.clearTimeout(rto);
			rto = window.setTimeout(function(){ 
				window.clearTimeout(rto);
				setwidth(menu);
				initcont(hortreecontainer);
				var api = hortreecontainer.data('jsp');
				if (api) {
					api.reinitialise();
				}
			}, 100);
		});
/*
*/
	});

	function sizerecalc(menu) {
		var hortreecontainer = menu.parents('.hortreecontainer');
		setwidth(menu);
		initcont(hortreecontainer);
		var api = hortreecontainer.data('jsp'), rto;
		if (api) {
//			if (!$.browser.msie) {
				api.reinitialise();
//			} else {
				rto = window.setTimeout(function() {
					window.clearTimeout(rto);
					api.reinitialise();
				}, 200);
//			}
		}
	}

	if ($.browser.msie && $.browser.version < 8) {
		$('.footer').css('display','none');
		window.setTimeout(function() {
			$('.footer').css('display','block');
		}, 200);
	}
	
	function initcont(cont) { // return false;
		cont.css('marginLeft',0);
		var offset = cont.offset(); offset = offset.left;
		cont.css({width:'10px'});
		var WW = $(window).width();
		cont.css({'marginLeft':'-'+offset+'px', width: WW});
		cont.find('.jspPane,.jspContainer').width(WW);
//        cont.find('.jspPane').css('marginLeft',0);
	}

	function setwidth(menu){
		var W = 0;
		menu.children('LI').each(function(){
			W += $(this).outerWidth(true);
		});
		menu.width(W+20);
	}
}
//end of closure
})(jQuery);


(function($) { //create closure
$.fn.mainmenulogic =	function(elem){
		var menu = $('.menu');
		var menupos = menu.offset();
		if(elem==undefined){
			elem='.horizontaltree header';
		}
		var tree = $(elem);
		var treepos = tree.offset();
		treepos = treepos.top + tree.outerHeight();
		if (treepos < menupos.top+menu.outerHeight()) {// если меню наезжает на структуру
			menu.after('<div class="menumore"><a href="#">ещё</a></div>');
			// menu.children('li').each(function(){
			menu.find('li').each(function(){
				var ofs = $(this).offset();
				if (ofs.top > treepos) {
					$(this).css('display','none').addClass('mustHide');
				}
			});
			var mm = menu.next('.menumore');
			mm.find('a').toggle(function(){
				menu.find('.mustHide').slideDown();
				menu.addClass('expanded');
				mm.addClass('expanded');
				return false;
			},function(){
				menu.find('.mustHide').slideUp();
				menu.removeClass('expanded');
				mm.removeClass('expanded');
				return false;
			});
		}
	}
})(jQuery);

$(document).ready(function(){
	window.setTimeout('$().mainmenulogic()',500); // подгонка меню под высоту шапки структуры
});

(function($) { //create closure
$.fn.inputoverlabel = function(options){
	var defaults = {
	};
	var errors = 0; var msg='';
	var opts = $.extend(defaults, options);

	var form = $(this);
	$('input[type=text],textarea', form).each(function(){
		var input = $(this);
		var label = $('label[for='+input.attr('id')+']');
		if (input.val()!='') label.addClass('hide');
		input.unbind('focus.hidelabel').bind('focus.hidelabel', function(){
			label.addClass('hide');
			input.parent().removeClass('error');
		});
		input.unbind('blur.showlabel').bind('blur.showlabel', function(){
			input.val($.trim(input.val()));
			if (input.val()=='') label.removeClass('hide');
		});
	});
}
//end of closure
})(jQuery);



(function($) { //create closure
$.fn.formpopup = function(options){
	var defaults = {
	};
	var errors = 0; var msg='';
	var opts = $.extend(defaults, options);

	var a = $(this);
	var form = $(a.attr('href'));
	if (form.length > 0) {
		form.hide();
                a.click(function(){
			form.show().dialog({
				modal: true,
				open: function(event, ui) {
				},
				width: 720,
				dialogClass: form.attr('id'),
				closeText: 'Закрыть форму', 
				resizable: false
			});
                	return false;
		});
	}
}
//end of closure
})(jQuery);





/* change font in blind page */	
/*
	$('.opt_btn.font_1').click(function(){
			$('.change_font').css('font-size','1em');
			return false;
	});
	$('.opt_btn.font_2').click(function(){
			$('.change_font').css('font-size','1.3em');
			return false;
	});
	$('.opt_btn.font_3').click(function(){
			$('.change_font').css('font-size','1.7em');
			return false;
	});
*/
/* /change font in blind page */


(function($) { //create closure
$.fn.initBlindPage = function(options){
	var defaults = {
		bodyclass: ''
	};
	var errors = 0; var msg='';
	var o = $.extend(defaults, options);
	var cont = $(this);
	var body = $('body');
	body.removeAttr('class');
	// init on page load
	var blind = $.cookie('blindclass');
	$('.blind_panel_opt .current').removeClass('current'); // убиваем отметки с current opt_btn
	$('.blind_panel_opt').each(function(){ // по-умолчанию устанавливаем current для каждой первой opt_btn в блоке
		$(this).find('.opt_btn:eq(0), .ch_opt:eq(0), .color_sch:eq(0)').addClass('current');
		// обработчики клика по кнопкам опций
		$(this).find('a[rel]').click(function(){
			$('a[rel='+$(this).attr('rel')+']').each(function(){
			        var a = $(this);
				var par = a.parents('.blind_panel_opt');
				par.find('.current').removeClass('current');
				a.addClass('current'); // отмечаем кликнутую
			});
                        
			// пробегаем по опциям и из current собираем класс для body
			var newclass = '';
			$('.blind_panel_opt').each(function(){
				newclass += $(this).find('a.current[rel]').attr('rel') + ' ';
			});
			newclass = $.trim(newclass);
			$.cookie('blindclass', newclass.replace(/\s/g,"|"),{path:'/',expires:3652});
			body.removeAttr('class').addClass(newclass+' '+o.bodyclass);
			return false;
		});
	});
	$('#settingsbutton').click(function(){
		$(this).addClass('current');
		$('#blind_panel_extend').dialog({
				modal: true,
				open: function(event, ui) {
					var obj = $(this);
					$('#closesettings,.ui-widget-overlay').unbind('click.dclose').bind('click.dclose', function(){
						obj.dialog('close');
						$('#settingsbutton').removeClass('current');
					});
				},
				close: function() {
					$('#settingsbutton').removeClass('current');
				},
				width: 610,
				minHeight: 520,
				dialogClass: 'blind_popup',
				closeText: 'Закрыть панель', 
				resizable: false
		});
	});
	$('#resetsettings').click(function(){
		$('.blind_panel_opt .current').removeClass('current');
		$('.blind_panel_opt').each(function(){
			$(this).find('.opt_btn:eq(0), .ch_opt:eq(0), .color_sch:eq(0)').addClass('current');
		});
		if(typeof(SetLogo) == "function"){
			SetLogo("cs1");
		}
		body.removeAttr('class').addClass(o.bodyclass);
		$.cookie('blindclass', null);
	});

	if (blind && blind.length > 0) { // смотрим, что было в куке
		body.addClass(blind.replace(/\|/g,' ')+' '+o.bodyclass);
		if(typeof(SetLogo) == "function"){
			for($i=1; $i<6; $i++){if(blind.replace(/\|/g,' ').indexOf("cs"+$i) !== -1){SetLogo("cs"+$i)}}
		}
		blind = blind.split('|');
		for (var i=0; i<blind.length; i++) {
			var optbtn = $('a[rel='+blind[i]+']');
			if (optbtn.length > 0) { // если есть ссылка с соответствущим классу из cookie атрибутом rel 
				var par = optbtn.parents('.blind_panel_opt');
				par.find('.current').removeClass('current');
				optbtn.addClass('current'); // то ее и отмечаем
			}
		}
	} else {
		body.addClass(o.bodyclass);
	}
}
//end of closure
})(jQuery);

	
	
	
function textErrorObserver() {
	var form = $('#errormessagesform');
	if (form.length > 0) {
		$(document).on('keydown.ctrlenter', function(e){
			if (e.keyCode==13 && e.ctrlKey) { // Ctrl + Enter
                        	e.stopPropagation();
				var seltxt = '';
				if (window.getSelection) {
					seltxt = window.getSelection();
				} else if (document.getSelection) {
					seltxt = document.getSelection();
				} else if (document.selection) {
					seltxt = document.selection.createRange().text;
				}
				$('#c_url').val(window.location.href);
				$('#c_errtext').val(seltxt);

				form.dialog({
					width: 720,
					height: 565,
					modal: true,
					closeText: 'Закрыть форму',
					dialogClass: 'errormessagesform',
					open: function(event, ui){
						var obj = $(this);
						$('.ui-widget-overlay').unbind('click.dclose').bind('click.dclose', function(){
							obj.dialog('close');
						});
					}
				});
			}
		});
	}
}


(function($) { //create closure
$.fn.smssubscribe = function(options){
	var defaults = {
	};
	var errors = 0; var msg='';
	var opts = $.extend(defaults, options);
	var cont = $(this);
	cont.each(function(){
		var form1 = cont.find('.sms_step_1');
		var form2 = cont.find('.sms_step_2');
		var form3 = cont.find('.sms_step_3');
		form1.find(':button').click(function(){ form1.submit(); })
		form2.find(':button').click(function(){ form2.submit(); })
		form1.bind('submit',function(){ // отправка первой формы
			form1.slideUp(250);
			form2.slideDown(250, function(){
			});
			return false;
		});
		form2.bind('submit',function(){ // отправка первой формы
			form2.slideUp(250);
			cont.find('.subsmsopener').remove();
			form3.css('display', 'block');
			return false;
		});
		cont.find('.subsmsopener').click(function(){
			form1.slideDown(250);
			return false;
		});
	});
}
//end of closure
})(jQuery);

function answerOpen(){
	$('.mainfaq dt .pseudolink').each(function(){
	var quest = $(this);
	var answer = $('.mainfaq dd p');
	answer.hide();
    quest.click(function(){
		
		quest.parent().next('dd').find('p').toggle();
		quest.toggleClass('pseudolink');
         return false;
	});
		});
}

/* function blindCur(){
	$('.blind_page').each(function(){
		var curLi = $(this).find('.menu li');

		curLi.click(function(){
			curLi.removeClass('current');
			$(this).addClass('current');
			$(this).parent().parent().next('.rubr').show();
		});
        return false;
	});
}
 */
 function blindCur(){
	$('.blind_page').each(function(){
		var curLi = $(this).find('.menu li[data-rubr]');
		curLi.click(function(){
			var curLiN = $(this).attr('data-rubr');
			$(this).parent().nextAll('ul[data-rubr]').hide();
			var curUlCur=$(this).parent().nextAll('ul[data-rubr="'+curLiN+'"]');
			curLi.removeClass('current');
			$(this).addClass('current');
			curUlCur.show();
		});
		var subCurLi = $(this).parent().find('ul[data-rubr] li');
		subCurLi.click(function(){
			var subtxt = $(this).text();
			subCurLi.removeClass('current');
			$(this).addClass('current');
		});
        return false;
	});
}


/* arrow nav */

document.onkeydown = NavigateThrough;

var focusInInput = false;

if (document.getElementsByTagName)
    onload = function () {
        var e, i = 0;
        while (e = document.getElementsByTagName('INPUT')[i++]) {
            if (e.type == 'text' || e.type == 'search') e.onfocus = function () {focusInInput = true};
            if (e.type == 'text' || e.type == 'search') e.onblur = function () {focusInInput = false};
        }
        i = 0;
        while (e = document.getElementsByTagName('TEXTAREA')[i++]) {
            e.onfocus = function () {focusInInput = true};
            e.onblur = function () {focusInInput = false};
        }
    };

function NavigateThrough (event) {
	if (!document.getElementById) return;

	if (window.event) event = window.event;

	if ((event.ctrlKey || event.altKey) && !focusInInput){
		var link = null;
		var href = null;
		switch (event.keyCode ? event.keyCode : event.which ? event.which : null){
			case 0x25:
				link = document.getElementById ('NextLink');
				break;
			case 0x27:
				link = document.getElementById ('PrevLink');
				break;
			case 0x26:
				link = document.getElementById ('UpLink');
				break;
			case 0x28:
				link = document.getElementById ('DownLink');
				break;
			case 0x24:
				href = '/';
				break;
		}

		if (link && link.href) document.location = link.href;
		if (href) document.location = href;
	}			
}

jQuery(function(){
  if(jQuery('.howcr').size() > 0){
    if(navigator.userAgent.toLowerCase().indexOf("mac os x 10_7")!=-1){
      jQuery('.howcr').html('Alt');
    }
  }
}); 

/* /arrow nav */




/* slider for content */
$(function() {

var hwSlideSpeed = 700;
var hwTimeOut = 3000;
var hwNeedLinks = true;
 
$(document).ready(function(e) {
    $('#slider .slide').css(
        {"position" : "absolute",
         "top":'0', "left": '0'}).hide().eq(0).show();
    var slideNum = 0;
    var slideTime;
    slideCount = $("#slider .slide").size();
    var animSlide = function(arrow){
        clearTimeout(slideTime);
        $('#slider .slide').eq(slideNum).fadeOut(hwSlideSpeed);
        if(arrow == "next"){
            if(slideNum == (slideCount-1)){slideNum=0;}
            else{slideNum++}
            }
        else if(arrow == "prew")
        {
            if(slideNum == 0){slideNum=slideCount-1;}
            else{slideNum-=1}
        }
        else{
            slideNum = arrow;
            }
        $('#slider .slide').eq(slideNum).fadeIn(hwSlideSpeed, rotator);
        $(".control-slide.active").removeClass("active");
        $('.control-slide').eq(slideNum).addClass('active');
        }
if(hwNeedLinks){
var $linkArrow = $('<a id="prewbutton" href="#"></a><a id="nextbutton" href="#"></a>')
    .prependTo('#slider');      
    $('#nextbutton').click(function(){
        animSlide("next");
 
        })
    $('#prewbutton').click(function(){
        animSlide("prew");
        })
}
    var $adderSpan = '';
    $('#slider .slide').each(function(index) {
            $adderSpan += '<span class = "control-slide">' + index + '</span>';
        });
    $('<div class ="sli-links">' + $adderSpan +'</div>').appendTo('#slider-wrap');
    $(".control-slide:first").addClass("active");
     
    $('.control-slide').click(function(){
    var goToNum = parseFloat($(this).text());
    animSlide(goToNum);
    });
    var pause = false;
    var rotator = function(){
    if(!pause){slideTime = setTimeout(function(){animSlide('next')}, hwTimeOut);}
            }
    $('#slider-wrap').hover(    
        function(){clearTimeout(slideTime); pause = true;},
        function(){pause = false; rotator();
        });
    rotator();
});

});


// ritual b-expander

$(document).ready(function() {

	(function($) {

		$('.b-expander').each(function() {
			var cont = $(this),
				link = '.b-expander_link',
				text = '.b-expander_text',
				jlink = $(link, cont),
				jtext = $(text, cont),
				el;

			jtext.each(function() {
				var el = $(this);
				el
					.data('height', el.height())
					.css('height', 0);
			});

			jlink
				.off('click.expander')
				.on('click.expander', cont, function() {
					var el = $(this),
						eltext = el.next(text);

					if (!eltext.hasClass('active')) {
						jlink.add(jtext).removeClass('active');
						jtext.css('height', 0);

						eltext.css('height', eltext.data('height'));
						el.add(eltext).addClass('active');
					} else {
						eltext.css('height', 0);
						el.add(eltext).removeClass('active');
					}
				});


			jlink.first().trigger('click.expander');

		});

	})(jQuery);

});


/* for mobile */
var mobile = (/iphone|ipad|ipod|android|blackberry|mini|windows\sce|palm/i.test(navigator.userAgent.toLowerCase()));
if(mobile){
	$('.scroll_hor').jScrollPane();
}
/* /for mobile */


window.onresize = function(event) {
  colorbox_eventday_resize();
}



