/* Author:

*/
$(function() {
	$('.iblock').cleanWS();
	$('.scroll').jScrollPane();
	if ($.browser.msie && $.browser.version < 9) {
		$('.colimg + .coltxt').addClass('iefixcoltxt');
		$('.coltxt + .colimg').addClass('iefixcolimg');
		$('.colimg + .aboutwork').addClass('iefixaboutwork');
	}
		$('.custom-checkbox').checkboxReplace();
	
	
	if ($.browser.msie && $.browser.version == 8) {
		$('.infoBlockList img').hover(
			function() {
				var that = $(this);
				that.animate({
					'height':'+=3px',
					'width':'+=0px'
				},200);
			},
			function() {
				var that = $(this);
				that.animate({
					'height':'-=3px',
					'width':'-=0px'
				},200);
			}
		);
	}
	
	$('.smiblock').click(function(){
		var smiblock = $(this),
		smitext = $('.smitext', smiblock),
		minHeight = 46,
    	autoHeight = smitext.css('height', 'auto').height(),
    	textopacity =  $('.textopacity', smiblock);
		
		
		smiblock.toggleClass('full');
		 smitext.css({height: minHeight});
		if ( smiblock.hasClass('full')) {	
			
			smitext.animate({					
					'height': autoHeight 				 			
				}, 400);
			textopacity.hide();
			
		} else {
			smitext.css({height: autoHeight});
			smitext.animate({
					'height': minHeight					
				},400);
			textopacity.show();
		}
	});
	
	
	$('.map_switcher .hidelink').click(function(){
		$('.viewmap').show(600);
		$('.maplayers').animate({ "right": "14px" }, "slow" );
		$(this).parents('.hidenmap').hide();
	});
	$('.map_switcher .close').click(function(){
		$('.hidenmap').show();
		$('.maplayers').animate({ "right": "-400px" }, "slow" );
		$(this).parents('.viewmap').hide();
	});
	
	
	
    $("#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(){
		if ($(window).width() > 1280) {
			var width = $(window).width() * 0.4;
		} else
		if ($(window).width() > 1024) {
			var width = $(window).width() * 0.6;
		} else {
			var width = $(window).width() * 0.9;
		}
		return width;
	},
    initialHeight:100,
    width: '60%',//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',
	reposition: true,
	fixed: true
  });


	$(window).on("resize", function(){
		if ($(window).width() > 1280) {
			var width = $(window).width() * 0.4;
		} else
		if ($(window).width() > 1024) {
			var width = $(window).width() * 0.6;
		} else {
			var width = $(window).width() * 0.8;
		}
		$.colorbox.resize({width: width})
	});

   


	
	$('.filterform .calend, .any_form__block .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);
			},
			onPageTransitionIn: function() {
				var prevPageLink = this.find('.photo-gallery_prev').css('visibility', 'hidden');
				var nextPageLink = this.find('.photo-gallery_next').css('visibility', 'hidden');
				
				// Show appropriate next / prev page links
				if (this.displayedPage > 0)
					prevPageLink.css('visibility', 'visible');

				var lastPage = this.getNumPages() - 1;
				if (this.displayedPage < lastPage)
					nextPageLink.css('visibility', 'visible');

				this.fadeTo('fast', 1.0);
			}
		};
		

		// Раздел media
		if ($(this).hasClass('__media')) {
			opts.enableBottomPager = false;
		}
		
		// для принудительного скрытия пагинации
		if ($(this).hasClass('__hide_pagination')) {
			opts.enableBottomPager = false;
		}

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

		gallery.find('.photo-gallery_prev').click(function(e) {
			gallery.previousPage();
			e.preventDefault();
		});

		gallery.find('.photo-gallery_next').click(function(e) {
			gallery.nextPage();
			e.preventDefault();
		});

/*
*/	
	}); // $('.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: 10,
        minScrollHeight: 20
  });

	if ($(window).width() < 1024) {
		$('#submitaquestion').parent('.ui-dialog').css({
			'width':'90%'
		});	
	} else {
		$('#submitaquestion').parent('.ui-dialog').css({
			'width':'68%'
		});	
	}

  
  var objSubordinate = $('.subordinate ol li');
	$.each(objSubordinate,function(){
		val = $(this);
		if ($(this,'last-child')) {
			$(this).append('<hr>');
		}
		$(this).find('.organization').css({
			'min-height': val.find('address').height() + 4
		})
	});
	$('.subordinate ol li:last-child hr').remove();
	
	if ($(window).width() < 1007) {
		$('.colwide').after('<div id="helpfull" style="clear:both;"></div>');
	} else {
		if ($('#helpfull')) {
			$('#helpfull').remove();
		}
	}
	
	$(window).resize(function() {
		if ($(window).width() < 1007) {
			$('.colwide').after('<div id="helpfull" style="clear:both;"></div>');
		} else {
			if ($('#helpfull')) {
				$('#helpfull').remove();
			}
		};
		
		$('.video_rating .ui-accordion-content-active').css({
			'height': 'auto !important'
		});
	});

	$('#submitaquestion').parent('.ui-dialog').css({
		'position':'absolute',
		'top':($(window).height() - $('#submitaquestion').height())/2 + 'px',
		'left':($(window).width() - $('#submitaquestion').width())/2 + 'px',
		'z-index':'1005',
		'outline':'none'
	});

	$('.IMP-item .calendar_add_link').css({
		'position':'relative',
		'right':'0px',
		'top':'0px'
	});

	if ($(window).width() < 1024) {
		$('#submitaquestion').parent('.ui-dialog').css({
			'width':'90%'
		});	
	} else {
		$('#submitaquestion').parent('.ui-dialog').css({
			'width':'68%'
		});	
	}


	$('#submitaquestion').parent('.ui-dialog').css({
		'position':'absolute',
		'top':($(window).height() - $('#submitaquestion').height())/2 + 'px',
		'left':($(window).width() - $('#submitaquestion').width())/2 + 'px',
		'z-index':'1005',
		'outline':'none'
	});
	$('#submitaquestion').find('dd').css({
		'border-bottom':'none'
	});	
	
	$(window).resize(function() {
		if ($(window).width() < 1024) {
			$('#submitaquestion').parent('.ui-dialog').css({
				'width':'90%'
			});	
		} else {
			$('#submitaquestion').parent('.ui-dialog').css({
				'width':'50%'
			});	
		}
		
		$('#submitaquestion').parent('.ui-dialog').css({
			'position':'absolute',
			'top':($(window).height() - $('#submitaquestion').height())/2 + 'px',
			'left':($(window).width() - $('#submitaquestion').width())/2 + 'px',
			'z-index':'1005',
			'outline':'none'
		});
		$('#submitaquestion').find('dd').css({
			'border-bottom':'none'
		});	
	});
	/**/
	
	$('.c-main-checkbox input:checkbox').subscribe_checkboxes();

}); // DOM loaded


(function($) {

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

			var th = $(this);
			
			th.click(function() {
				console.log('u');
				if ( th.prop('checked') == true ) {
					$('.c-option-checkboxes input:checkbox').prop('disabled', true).prop('checked', false);
					$('.c-option-checkboxes .rubric_items').hide();
					$('.c-option-checkboxes label').css({ 'opacity': .5 });
				}
				else {
					$('.c-option-checkboxes input:checkbox').prop('disabled', false);
					$('.c-option-checkboxes label').css({ 'opacity': 1 });
				}
			});

		});
	};

})(jQuery);

(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){
				carousel.container.parent().addPreloader();
			    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(){window.setTimeout(function(){carousel.container.parent().removePreloader()},150);});
							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(){window.setTimeout(function(){carousel.container.parent().removePreloader()},150);});
					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();
					if (api.getIsScrollableV()) {
						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();
		if(treepos!=undefined){
			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: function() {
					if ($(window).width() < 640) {
						return '90%'
					} else {
						return '60%'
					}
				},
				position: 'center center',
				dialogClass: form.attr('id'),
				closeText: 'Закрыть форму', 
				resizable: false
			});
			form.parent('.ui-dialog').css({
				'position':'absolute',
				'top':'381.5px'
			})
			if ($.browser.msie) {
				$('.ui-widget-overlay').insertBefore('.ui-dialog');
			}
            return false;
			
			form.find('dd').css({
				'border-bottom':'none'
			});	
			return false;
			if ($.browser.msie) {
				$('.ui-widget-overlay').insertBefore('.ui-dialog');
			}
            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 = ((quest.parent('dt')).next('dd'))//.children();
		answer.hide();
		
		quest.click(function(){
			answer.toggle();
			quest.toggleClass('pseudolink');
			quest.parent('dt').toggleClass('opened')
			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 parent = $(this).find("ul li[parent]");
		var childe = $(this).find("ul[childe] li.current").parent().show();
		parent.click(function(){
			var parent_attr = $(this).parent().attr('childe');
			$("ul[childe="+parent_attr+"] li").removeClass('current');
			$(this).addClass('current');	
			var parent_name = $(this).attr("parent");
			var childe=$('.blind_page').find("ul[childe="+parent_name+"]");
			if(childe[0]==undefined){
			}else{
				if(($(this).parent().attr('class'))!="rubr"){
					$("ul.rubr").hide();
				}
				childe.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');
			var curUlCur=$(this).parent().nextAll('ul[data-rubr="'+curLiN+'"]');
			if(curUlCur[0]!=undefined){
				$(this).parent().nextAll('ul[data-rubr]').hide();
				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 xH = 0;
			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() + parseInt(el.css('margin-top')) + parseInt(el.css('margin-bottom')))
					.css('height', 0);
			});
			
			if (($.browser.msie) && ($.browser.version == '8.0')) {
				$('.b-expander_text').each(function() {
					var xH_1 = $(this).children();
					var H = 0;
					$.each(xH_1, function() {
						H += $(this).height();
						if (!isNaN(parseInt($(this).css('margin-top')))) {
							H += parseInt($(this).css('margin-top'));
						};
						if (!isNaN(parseInt($(this).css('margin-bottom')))) {
							H += parseInt($(this).css('margin-bottom'));
						}
					});
					$(this).data('height',H);
					
				});
			}
			
			$(window).resize(function() {
				var arr = $('.b-expander_text.active').children();
				xH = 0;
				
				$('.b-expander_text').each(function() {
					var xH_1 = $(this).children();
					var H = 0;
					$.each(xH_1, function() {
						H += $(this).height();
						if (!isNaN(parseInt($(this).css('margin-top')))) {
							H += parseInt($(this).css('margin-top'));
						};
						if (!isNaN(parseInt($(this).css('margin-bottom')))) {
							H += parseInt($(this).css('margin-bottom'));
						}
					});
					$(this).data('height',H);
				});
				
				$.each(arr, function() {
					xH += $(this).height();
					if (!isNaN(parseInt($(this).css('margin-top')))) {
						xH += parseInt($(this).css('margin-top'));
					};
					if (!isNaN(parseInt($(this).css('margin-bottom')))) {
						xH += parseInt($(this).css('margin-bottom'));
					}
				});
				if (($.browser.msie) && ($.browser.version == '8.0')) {
					$('.b-expander_text.active').removeAttr('style');
					$('.b-expander_text.active').css({'height':xH + 'px'});
				}
				$('.b-expander_text.active').css({'height':xH + 'px'})
			});			
			
			
			jlink
				.off('click.expander')
				.on('click.expander', cont, function() {
					var el = $(this),
						eltext = el.next(text);
					if (($.browser.msie) && (($.browser.version == '8.0') || ($.browser.version == '9.0'))) {
						if (!eltext.hasClass('active')) {
							jtext.animate({
								'height':0  + 'px'
							},200, function(){
								jlink.add(jtext).removeClass('active');
								eltext.animate({
									'height': eltext.data('height') + 'px'
								},200);
								el.add(eltext).addClass('active');
								
							});
							
							
						} else {
							eltext.animate({
								'height':0  + 'px'
							},200, function () {
								jlink.add(jtext).removeClass('active');
							});
						}
					} else {
						if (!eltext.hasClass('active')) {
							jlink.add(jtext).removeClass('active');
							jtext.css({
								'height':0
							});
							el.add(eltext).addClass('active');
							eltext.css({
								'height':eltext.data('height')
							});
							
						} else {
							jlink.add(jtext).removeClass('active');
							eltext.css({
								'height':0
							});
						}
					}
				});
			jlink.first().trigger('click.expander');
		});
	})(jQuery);
});
(function($) { // Функция добавляющая прелоадер
	$.fn.addPreloader = function() {
		return this.each(function() {
			var obj = $(this);
				obj.css({
					'position':'relative'
				})
			var hg = $(this).height();
			var wd = $(this).width();
			var preloader = '<div class="preloader_bg"></div>'
			var loading = '<img src="/bitrix/templates/trp3_main_d3/images/loading.gif" class="preloader_progress">'
			obj.children().eq(0).before(preloader);
			preloader = $(this).children().eq(0);
			preloader.css({
				'height':hg + 'px',
				'width':wd + 'px'
			});
			preloader.html(loading);
		});
	};
})(jQuery);
(function($) {
	$.fn.showVideoPopUp = function() {
		return this.each(function() {
			var th = $(this);
			var shadow = $('body').find('.shadow_screen');
			var button = $('body').find('.show_pop_up');
			var close = th.find('.close_popUp')
			
			button.click(function() {
				if ($(window).width() < 525) {
					th.css('width','85%');
				} else {
					th.css('width','50%');
				}
				var position = [0,0];
					position[0] = ($(window).height() - th.height())/2;
					position[1] = ($(window).width() - th.width())/2;
				th.css({
					'top'	:	position[0] + 'px',
					'left'	:	position[1] + 'px'
				});
				shadow.show();
				th.show();
			});
			
			$(window).resize(function() {
				if ($(window).width() < 525) {
					th.css('width','85%');
				} else {
					th.css('width','50%');
				}
				var position = [0,0];
					position[0] = ($(window).height() - th.height())/2;
					position[1] = ($(window).width() - th.width())/2;
				th.css({
					'top'	:	position[0] + 'px',
					'left'	:	position[1] + 'px'
				});
				
				
			});
			
			close.click(function() {
				shadow.hide();
				th.hide();
			});
			
		});
	};
})(jQuery);
(function($) {
	$.fn.miniWindow = function() {
		return this.each(function() {
			var th = $(this);
			var obj = th.parent();
			
			th.hide();
			
			obj.hover(
				function() {
					th.show();
				},
				function() {
					th.hide();
				}
			);
		});
	};
})(jQuery);

(function($) { // Функция добавляющая прелоадер
	$.fn.addPreloader = function() {
		return this.each(function() {
			var obj = $(this);
			var hg = $(this).height();
			var wd = $(this).width();
			var preloader = '<div class="preloader_bg"></div>'
			var loading = '<img src="/bitrix/templates/trp3_main_d3/images/loading.gif" class="preloader_progress">'
			obj.children().eq(0).before(preloader);
			preloader = $(this).children().eq(0);
			preloader.css({
				'height':hg + 'px',
				'width':wd + 'px'
			});
			
			preloader.html(loading);
			
			loading = preloader.children('img');
			
			loading.css({
				'padding-top': ((preloader.height() - 26) / 2) + 'px',
				'padding-left': ((preloader.width() - 26) / 2) + 'px',
				'width': '26px'
			});
			
			
			
		});
	};
})(jQuery);

(function($) { // Функция удаляющая прелоадер
	$.fn.removePreloader = function() {
		return this.each(function() {
			obj = $(this).children().eq(0).remove();
		});
	};
})(jQuery);

/*****************************************************************/

//contacts
$(function() {
    var blockContact = $('.contact_info_caption').children();
    var mainComtact = $('.contact_info_caption').find('.contact_info_main');
    var schemeComtact = $('.contact_info_caption').find('.contact_info_scheme');
    var bankComtact = $('.contact_info_caption').find('.contact_info_bank');
    
    schemeComtact.hide();
    bankComtact.hide();
    
    $('.building_fotos').miniSlider();
    
    $('.contact_info_labels ul li').click(function() {
        blockContact.hide();
        $('.contact_info_labels ul li').removeClass('active');
        $(this).addClass('active');
        if ($(this).hasClass('contact')) {
            $('.contact_info_main').show();
        } else
        if ($(this).hasClass('scheme')) {
            $('.contact_info_scheme').show();
        } else
        if ($(this).hasClass('bankInfo')) {
            $('.contact_info_bank').show();
        };
    })
});

(function($) {
    $.fn.miniSlider = function() {
        return this.each(function() {
            var slider = $(this);
            var preview = slider.find('.building_fotos_navigator_preview');
            var nextArrow = slider.find('.building_fotos_navigator_right span');
            var prevArrow = slider.find('.building_fotos_navigator_left span');
            var previewPic = slider.find('.preview_wrapper');
            var screen = slider.find('.building_foto img');
            
            var currentPic, nextPic, prevPic;
            
            previewPic.click(function() {
                var $src = $(this).children('img').attr('src');
                screen.attr('src',$src);
                previewPic.removeClass('active');
                $(this).addClass('active');
                currentPic = $(this);
                if ($(this).next().length == 0) {
                    nextPic = previewPic.eq(0);
                } else {
                    nextPic = $(this).next();
                };
                
                if ($(this).prev().length == 0) {
                    prevPic = previewPic.eq(previewPic.length - 1);
                } else {
                    prevPic = $(this).prev();
                };
            });
            
            prevArrow.click(function() {
                prevPic.trigger('click');
            });
            
            nextArrow.click(function() {
                nextPic.trigger('click');
            });
            
            previewPic.eq(0).trigger('click');
        });
    }
})(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 */

$(function() {
	$('.request_info_labels').tabSwitcher();
});

(function($) {
	$.fn.tabSwitcher = function() {
		return this.each(function() {
			var th = $(this);
			var tabs = th.find('.contact_info_label');
			
			tabs.click(function() {
				var className = $(this).attr('class').split(' ');
					className = className[0];
				var objClassName = $('body').find('div.' + className).attr('class').split(' ');
					objClassName = '.' + objClassName[1];
					className = 'div.' + className;
					
				
				tabs.removeClass('active');
				$(this).addClass('active');
				$(objClassName).hide();
				$(className).show();
				
			});
			tabs.eq(0).trigger('click');
		});
	};
})(jQuery);		

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

function resizeVideoInput() {
	var wdth = $('.video_editor').width() - 125;
	$('.video_info').width(wdth);
}

function removeVideo(obj) {
	var obj = $(obj.target).parents('.video_editor');
		obj.remove();
	if ($('.inactive').length == 0) {
		$('.video_editor').eq(0).find('.cover_switcher .pseudo_link').trigger('click');
	};
}

function addNewDirection() {
	var yourClick_1 = true;
	var bar = '<div class="form_box current_box"><span class="name current_name"></span><span class="remove"></span></div>';
	var place = $('.directions_container');
		place.append(bar);
		$('.form_box.current_box').hide();
	
	$('.form_box .remove').live('click',removeDirection);
	
	var posX = ($(this).width() - $('.for_Directions').width())/2;
	var posY = $(this).height() + 25;
	$('.add_new_direction').parent().css({
		'position':'relative'
	});
	$('.for_Directions')
		.css({
			'left':posX + 'px',
			'top':posY + 'px'
		})
		.show();
	$('.name_of_new_direction').focus();
	$(document).bind('click.myEvent_1', function(e) {

		if (!yourClick_1 && $(e.target).closest('.for_Directions').length == 0) {
			$('.for_Directions').hide();
			$('.current_box').remove();
			$(document).unbind('click.myEvent_1');
		};
		yourClick_1 = false;
	});
	$('.confirm_change').bind('click',function() {
		if ($('.name_of_new_direction').val() != '') {
			var value = $('.name_of_new_direction').val()
			$('.form_box.current_box .name.current_name').text(value);
			$('.for_Directions').hide();
			$('.form_box.current_box .name.current_name').removeClass('current_name');
			$('.form_box.current_box')
				.show()
				.removeClass('current_box');
			$('.name_of_new_direction').val('');
			yourClick_1 = false;
		}
	});
	$(document).bind('keypress',function(e) {
		if (e.keyCode == 13) {
			if ($('.name_of_new_direction').val() != '') {
				var value = $('.name_of_new_direction').val()
				$('.form_box.current_box .name.current_name').text(value);
				$('.for_Directions').hide();
				$('.form_box.current_box .name.current_name').removeClass('current_name');
				$('.form_box.current_box')
					.show()
					.removeClass('current_box');
				$('.name_of_new_direction').val('');
				yourClick_1 = false;
			}
		}
	});
}
function resizeBlocks(obj) {
	var wdth = $('.full_popUp .form_caption').width() - 54;
	obj.width(wdth);
}
// Rate Function
(function($) {
	$.fn.ratevideo = function() {
		return this.each(function() {
			var rateStar = $(this).find('.video_mark .rate_star');
			var markPlace = $(this).find('.video_mark input');
			var markGetted = $(this).parents('.ui-accordion-content').prev('h3').find('.rate_star');
			var markLabel = $(this).parents('.ui-accordion-content').prev('h3').find('.mark_label');
			var content = $(this).parents('.ui-accordion-content');
			
			
			rateStar.hover(
				function() {
					var prevElems = $(this).prevAll();
					var nextElems = $(this).nextAll();
					
					nextElems.each(function() {
						if ($(this).hasClass('selected')) {
							$(this).addClass('default');
						};
					});
					
					prevElems.each(function() {
						if ($(this).hasClass('selected')) {
							$(this).addClass('moused');
						};
						if ($(this).hasClass('default')) {
							$(this).addClass('moused');
						};
					});
				},
				function() {
					var prevElems = $(this).prevAll();
					var nextElems = $(this).nextAll();
					
					nextElems.each(function() {
						if ($(this).hasClass('selected')) {
							$(this).removeClass('default');
						};
					});
					
					prevElems.removeClass('moused');
					nextElems.removeClass('moused');
				}
			);
			
			rateStar.click(function() {
				var prevElems = $(this).prevAll();
				var nextElems = $(this).nextAll();
				
				$(this).removeClass('default').addClass('selected');
				
				nextElems.each(function() {
					$(this).removeClass('selected').addClass('default');
				});
				
				prevElems.each(function() {
					$(this).removeClass('default').addClass('selected');
				});
				
				var videoRate = $(this).length + prevElems.length;
				
				if (videoRate > 0) {
					markGetted.hide();
					markLabel.hide();
					markGetted.each(function(i) {
						if (i < videoRate) {
							$(this).show();
						}
					});
				}
				markPlace.val(videoRate);
				
				console.log(videoRate)
			});
		});
	};
})(jQuery);				
$(function() {
	if ($('#submitaquestion').length > 0) {
		var th = $('#submitaquestion').parent('.ui-dialog');
		th.css({
			'position':'absolute',
			'top':($(window).height() - $('#submitaquestion').height())/2 + 'px',
			'left':($(window).width() - $('#submitaquestion').width())/2 + 'px',
			'z-index':'1005',
			'outline':'none'
		});
	}
});

(function($) {
	$.fn.checkboxReplace = function(options){
		var cont = $(this),
			input = cont.find('input[type="checkbox"]'),
			label = cont.find('label');

		input.each(function() {
			var name = $(this).attr('name'),
				id = $(this).attr('id'),
				replacer = $('<div class="checkbox-replacer"></div>');

			$(this).css({
				'position': 'absolute',
				'left': '-9999px'
			});

			replacer
				.attr({
					'data-name': name,
					'data-id': id
				})
				.insertAfter($(this))
				.on('click', cont, function() {

					label.filter('[for="' + id + '"]').click();

				});

			if ($(this).prop('checked')) {
				replacer.addClass('selected');
			} 

		});

		label.each(function() {
			var for_attr = $(this).attr('for');

			$(this).on('click', cont, function() {

				var replacer = $('.checkbox-replacer[data-id="' + for_attr + '"]'),
					name = replacer.attr('data-name');

			/*	$('.checkbox-replacer[data-name="' + name + '"]')
					.removeClass('selected');*/
				
				
				if (replacer.hasClass('selected')) {
				replacer.removeClass('selected');
				} else {
					replacer.addClass('selected');
				}

			});

		});
	};
})(jQuery);
(function($) { //create closure
$.fn.cleanWS = function(options){
	this.each(function(){
		var iblock = this, par = iblock.parentNode, prev = iblock.previousSibling, next = iblock.nextSibling;
		while (prev) {
			var newprev = prev.previousSibling;
			if (prev.nodeType == 3 && prev.nodeValue) {
				for (var i=prev.nodeValue.length-1; i>-1; i--) {
					var cc = prev.nodeValue.charCodeAt(i);
					if (cc==9||cc==10||cc==32) {
						prev.nodeValue = prev.nodeValue.slice(0,i);
					} else {
						break;
					}
				}
			}
			if (prev.nodeType == 8)	par.removeChild(prev); // remove comment
			prev = newprev;
		}
		while (next) {
			var newnext = next.nextSibling;
			if (next.nodeType == 3 && next.nodeValue) {
				while(next.nodeValue.length) {
					var cc = next.nodeValue.charCodeAt(0);
					if (cc==9||cc==10||cc==32) {
						next.nodeValue = next.nodeValue.slice(1);
					} else {
						break;
					}
				}
			}
			if (next.nodeType == 8)	par.removeChild(next); // remove comment
			next = newnext;
		}

	});
}
//end of closure
})(jQuery);
