function secE(){
	
	$('.obj-filter .dd-item-c a').click(function(){
		if ($(this).closest('.sub').length <= 0){
			$(this).closest('.dd-item-c').toggleClass('open-item');
			return false;
		}
	});
	$('#content .obj-filter .wider-search a').click(function(){
		$(this).closest('.wider-search').toggleClass('open-item');
		$('.wider-search-container').toggle();
		return false;
	});
	var hideFilterItem = $('body').bind('click',function(e){
		if ($(e.target).closest('.dd-item-c').length <= 0){
			$('.dd-item-c.open-item').removeClass('open-item');
			$("body").unbind("click", hideFilterItem);
		}
	});
	
	$('#content .obj-filter .characters .sub input[type="checkbox"]').each(function(){
		if ($(this).is(':checked')){
			$(this).closest('p').addClass('checked');
		}
		else{
			$(this).closest('p').removeClass('checked');
		}
	});
	var defHtml = $('#content .obj-filter .characters a').text(), button = '<ins class="b-dropdown-button"></ins>';
	var checkText = defHtml+':';
	$('#content .obj-filter .characters p.checked').each(function(){
		checkText += $(this).text()+', ';
	});
	checkText += button;
	$('#content .obj-filter .characters a').html(checkText);
	$('#content .obj-filter .characters .sub input[type="checkbox"]').change(function(){
		checkText = defHtml+': ';
		
		if ($(this).is(':checked')){
			$(this).closest('p').addClass('checked');
		}
		else{
			$(this).closest('p').removeClass('checked');
		}
		$('#content .obj-filter .characters p.checked').each(function(){
			checkText += $(this).text()+', ';
		});
		checkText += button;
		$('#content .obj-filter .characters a').html(checkText);
	});
	
	$('.listing-obj .corpuses a').live('click',function(){
		$('.corpuses b',$(this).closest('.objects-item')).toggle();
                
		$('.add-info .price',$(this).closest('.objects-item')).toggle();
		$('.corpuses-list',$(this).closest('.objects-item')).toggle();
                $('.location .webcam_popup',$(this).closest('.info')).toggle();
		$('.icons',$(this).closest('.info')).toggle();
                $('.add-info .firma',$(this).closest('.objects-item')).toggle();
		$('.corpuses-list .icons',$(this).closest('.info')).show();
		$(this).html($.trim($(this).text()) == 'свернуть корпуса' ? '<span>раскрыть</span><ins class="b-dropdown-button"></ins>' : '<span>свернуть корпуса</span><ins class="b-dropdown-button b-dropup-button"></ins>');
		return false;
	});
}

function unNumeralObjectList(){
	$('.numeral').remove();
}
function numeralObjectList(){
	$('.objects-item:visible').each(function(i){
		$('<img/>',{'src':'/marker.orange'+(i+1)+'.png','class':'numeral'}).appendTo($(this));
	});
}
(function($){
	function openSub(){
		$('.realty_menu_sub').click(function(){
			if ($('.realty_menu_sub_item',$(this).closest('div')).length > 0){
				$('.realty_menu_sub_item',$(this).closest('div')).slideToggle();
				$(this).toggleClass('open');
				if ($(this).hasClass('open')) 
					$('.realty_menu_sub_item:eq(0) div',$(this).closest('div')).show();
					$('.realty_menu_sub_item:eq(0) .realty_menu_sub_sub_item').addClass('openSub');
			}
			return false;
		});
		$('.realty_menu_sub_sub_item').click(function(){
			if ($('div',$(this).closest('.realty_menu_sub_item')).length > 0){
				$('div',$(this).closest('.realty_menu_sub_item')).slideToggle();
				$(this).toggleClass('openSub');
			}
			return false;
		});
	}
	function sValidate(){}
	sValidate.prototype = {
		init: function(){
			var self = this;
			//console.log('!');
			this.expR = {};
			this.expR.email = /\b[-0-9a-zA-Z_.]*?\@[-0-9a-zA-Z_]*?\.[-0-9a-zA-Z_]{2,4}\b/;
			this.form = $('.s-validate');
			
			this.submitForm(self);
			
			$('#send_page').click(function(){
				var interval = setInterval(function(){
					if ($('.p-body .s-validate').length){
						self.form = $('.s-validate');
						self.submitForm(self);
						clearInterval(interval);
					}
				},100);
			});
		},
		submitForm: function(self){
			this.form.each(function(){
				$(this).submit(function(){
					$(':submit',this).removeClass('submitting');
					$('input[name="email"]',this).val().match(self.expR.email) ? self.valid($(this),$('input[name="email"]',$(this))) : self.invalid($(this),$('input[name="email"]',$(this)));
					if(!($(this).hasClass('form_invalid')) && ($(this).hasClass('subscribe_form') || $(this).hasClass('aj-resp'))){
						self.response($(this),self);
						return false;
					}
					if ($(this).hasClass('form_invalid')){
						return false;
					}
				});
				$('input[name="email"]',this).blur(function(){
					if ($(this).val() != '')
						$(this).val().match(self.expR.email) ? self.valid($(this).closest('form'),$(this)) : self.invalid($(this).closest('form'),$(this));
				});
				$('input[name="email"]',this).focus(function(){
					$(this).closest('form').removeClass('form_invalid');
					$(this).removeClass('invalid');
				});
			});
		},
		invalid: function(form,elem){
			elem.removeClass('valid').addClass('invalid');
			form.addClass('form_invalid');
		},
		valid: function(form,elem){
			elem.removeClass('invalid').addClass('valid');
			form.removeClass('form_invalid');
		},
		response:function(form,self){
			$('label,.s-submit',form).hide();
			if (form.hasClass('subscribe_form')){
				var dataSend = {
					'email':form.find('input[name="email"]').val(),
					'list_id':form.find('input[name="list_id"]').val(),
					'groups_id':form.find('input[name="groups_id"]').val(),
					'group_id':form.find('input[name="group_id"]').val()
				}
				$.post(window.location.protocol + '//' + window.location.host +'/@@subscriptions',dataSend,function(data){
					if (data == 'True' || data == true) form.removeClass('form_invalid').addClass('form_valid').html('Вы подписали эл. почту '+dataSend.email+' на рассылку новостей '+$('h1.documentFirstHeading').text());
					else{
						form.removeClass('form_valid').addClass('form_invalid').html('Не удалось осуществить подписку, обратитесь к администрации сайта.');
					}
				});
				//form && form.removeClass('form_invalid').addClass('form_valid').html('Вы подписали эл. почту '+$('input[name="email"]',form).val()+' на рассылку новостей '+$('input.title',form).val());
				
			}
			else if (form.hasClass('sendLink-p')){
				var h = $('<h2/>',{'html':'Ссылка отправлена'});
				var mail = $('input[name="email"]',form).val();
				var from = ($('.name',form).length > 0 && $('.name',form).val() != '' ? '<div class="field"><span>От:</span>'+$('.name',form).val()+'</div>' : '');
				var comment = ($('.comment',form).length > 0 && $('.comment',form).val() != '' ? '<div class="field">'+$('.comment',form).val()+'</div>' : '');
				var s = $('<div/>',{'html':'<div class="field"><span>Кому:</span>'+mail+'</div>'+from+comment});
				form.html('');
				h.appendTo(form);
				s.appendTo(form);
			}
		}
	}
	function gallery(){}
	gallery.prototype = {
		init:function(){

			var self = this;
			this.vGalleryContainer = $('.v-gallery-container');
			this.vGallery = $('.v-gallery .v-gallery-img-list');
			this.hGallery = $('.h-gallery .h-gallery-slide-container');
			
			
			this.chooseImgByButton();
			this.hGalleryEvts(self);
			this.vGalleryEvts(self);
			this.mountEvts(self);
			this.slideByDates(self);
                        //alert($('.h-gallery-slide-container .jspPane').css('top'));
                        $('.h-gallery-slide-container .jspPane').css('top', '');

		},
		chooseImgByButton: function(){
			$('.v-gallery-container .v-button').live('click',function(){
				if ($(this).hasClass('v-l')){
					var activeElem = $('.popup .v-gallery .v-gallery-img-list a.active');
					if ($('.popup .v-gallery .v-gallery-img-list a.active').prev().length > 0){
						$('.popup .v-gallery .v-gallery-img-list a.active').prev().addClass('active');
					}
					else{
						$('.popup .v-gallery .v-gallery-img-list a:last-child').addClass('active');
					}
					activeElem.removeClass('active');
				}
				else{
					var activeElem = $('.popup .v-gallery .v-gallery-img-list a.active');
					if ($('.popup .v-gallery .v-gallery-img-list a.active').next().length > 0){
						$('.popup .v-gallery .v-gallery-img-list a.active').next().addClass('active');
					}
					else{
						$('.popup .v-gallery .v-gallery-img-list a:first-child').addClass('active');
					}
					activeElem.removeClass('active');
				}
				$('.v-gallery-popup .v-gallery-img-list a').each(function(i){
					if ($('.v-gallery-popup .v-gallery-img-list a:eq('+i+')').hasClass('active') && (i-1) >= 0){
						$('.v-gallery-desc .v-gallery-img-list a:eq('+(i-1)+')').addClass('active');
					}
				});
				$('.p-body .v-gallery h2').remove();
				$('.v-gallery-v .description').remove();
                                $('.v-gallery-container .description').remove();
				$('.popup .v-gallery-main-pic img').attr('src',$('.popup .v-gallery .v-gallery-img-list a.active').attr('href'));
				$('.popup .v-gallery .v-gallery-img-list a.active').attr('title') && $('.popup .v-gallery .v-gallery-img-list a.active').attr('title') != '' ? $('<h2/>',{'html':$('.popup .v-gallery .v-gallery-img-list a.active').attr('title')}).insertBefore($('.v-gallery-main-pic',$('.p-body .v-gallery'))) : '';
				$('.popup .v-gallery .v-gallery-img-list a.active').attr('rel') && $('.popup .v-gallery .v-gallery-img-list a.active').attr('rel') != '' ? $('<div/>',{'class':'description','html':$('.popup .v-gallery .v-gallery-img-list a.active').attr('rel')}).appendTo($('.p-body .v-gallery').closest('.v-gallery-container')) : '';
				$('.v-gallery-desc .v-gallery-img-list .active').removeClass('active');
				
				if ($('.v-gallery-h .v-gallery-img-list .active').hasClass('webcamera')){
                	var webcam = $('.v-gallery-desc .v-gallery-img-list .active').find('img');
					$('.popup .v-gallery-main-pic img').hide();
						gallSWF(webcam.attr('src'), webcam.attr('data-bigimg'),  webcam.attr('camtype'));
				}
				else{
					$('.v-gallery-web').html('<div id="v-gallery-web"></div>');
					$('.popup .v-gallery-main-pic img').show();
				}
			});
		},
		hGalleryEvts: function(){
			var hgalleryimglist = '',head = '',desc = '';
                        //alert($('.h-gallery-slide-container .jspPane').css('top'));
                        //$('h-gallery-slide-container .jspPane').css('top','');
			$('.h-gallery-slide-area li').each(function(i){
				head = ($(this).attr('title') ? $(this).attr('title') : '');
				desc = ($(this).attr('rel') ? $(this).attr('rel') : '');
				if ($(this).hasClass('webcamera')){
					hgalleryimglist += '<a class="webcamera" camtype="'+$('img',this).attr('camtype')+'"title="'+$(this).attr('title')+'" href="'+$('img',this).attr('data-bigimg')+'"><img width="77" height="55" src="'+$('img',this).attr('src')+'" camtype="'+$('img',this).attr('camtype')+'" alt="" /></a>'
				}
				else {
					hgalleryimglist += '<a title="'+head+'" rel="'+desc+'" href="'+$('img',$(this)).attr('data-bigimg')+'"><img width="77" height="55" src="'+$('img',$(this)).attr('rel')+'" alt="" /></a>';
				}
			});

                        //alert('popup');
			var html =  '<b class="v-button v-l"></b><b class="v-button v-r"></b><div class="v-gallery v-gallery-h">'+
							'<div class="v-gallery-main-pic">'+
								'<div class="v-gallery-web"><div id="v-gallery-web"></div></div>'+
								'<img class="main" src="/content_img/h-gallery-1.png">'+
							'</div>'+
							'<div class="v-gallery-img-list">'+hgalleryimglist+
							'</div>'+
						'</div>';
			$('.v-gallery-h .v-gallery-img-list a').live('click',function(){
				$('.v-gallery-main-pic img').show();
				$('.v-gallery-h h2').remove();
				$('.v-gallery-h .description').remove();
				$(this).attr('title') && $(this).attr('title') != '' ? $('<h2/>',{'html':$(this).attr('title')}).insertBefore($('.v-gallery-main-pic',$('.v-gallery-h'))) : '';
				$(this).attr('rel') && $(this).attr('rel') != '' ? $('<div/>',{'class':'description','html':$(this).attr('rel')}).appendTo($('.v-gallery-h').closest('.v-gallery-container')) : '';
			});
			var gContainer = $('<div/>',{'html':html,'class':'v-gallery-container'});
			$('.h-gallery-slide-area li').click(function(){
				if ($(this).closest('.content_gallery').length) return;
				
				if (!$('.v-gallery-popup').length){
					popup(gContainer,'v-gallery-popup');
					$(this).attr('title') && $(this).attr('title') != '' ? $('<h2/>',{'html':$(this).attr('title')}).insertBefore($('.v-gallery-main-pic',gContainer)) : $('.v-gallery-popup h2').remove();
					$(this).attr('rel') && $(this).attr('rel') != '' ? $('<div/>',{'class':'description','html':$(this).attr('rel')}).appendTo(gContainer) : $('.v-gallery-popup .description').remove();
					$('.popup .v-gallery .v-gallery-img-list').jScrollPane({
						verticalDragMinHeight: 21,
						verticalDragMaxHeight: 21
					});
				}
				else{
					$('.v-gallery-popup h2').remove();
					$('.v-gallery-popup .description').remove();
					$(this).attr('title') && $(this).attr('title') != '' ? $('<h2/>',{'html':$(this).attr('title')}).insertBefore($('.v-gallery-main-pic',gContainer)) : '';
					$(this).attr('rel') && $(this).attr('rel') != '' ? $('<div/>',{'class':'description','html':$(this).attr('rel')}).appendTo(gContainer) : '';
					$('.v-gallery-popup').show();
				}
				$('.popup .v-gallery .v-gallery-img-list a.active').removeClass('active');
				$('.popup .v-gallery .v-gallery-img-list a:eq('+$(this).index()+')').addClass('active');
				$('.popup .v-gallery-main-pic img').attr('src',$('img',$(this)).attr('data-bigimg'));
				if ($(this).hasClass('webcamera')){
                	var webcam = $(this).find('img');
					$('.popup .v-gallery-main-pic img').hide();
						gallSWF(webcam.attr('src'), webcam.attr('data-bigimg'), webcam.attr('camtype'));
				}
				else{
					$('.v-gallery-web').html('<div id="v-gallery-web"></div>');
				}
			});
			$('.v-gallery-img-list .webcamera').live('click',function(){
				$('.popup .v-gallery-main-pic img').hide();
				gallSWF($(this).find('img').attr('src') ,$(this).attr('href'), $(this).attr('camtype'))
			});
                        //$('.h-gallery-slide-container .jspPane').css('top', '');

		},
		vGalleryEvts: function(self){
			//$('.v-gallery-container .active').removeClass('active');
			hidePopup('.v-gallery-popup');
			var gContainer = this.vGalleryContainer.clone().removeClass('v-gallery-desc').addClass('v-gallery-v');
                        var counter = 0;
                        $('.v-gallery .v-gallery-img-list a').each(function(){counter = counter +1;})
                        //alert('popup');
                        if (counter > 0){
                          $('<b/>',{'class':'v-button v-l'}).appendTo(gContainer);
			  $('<b/>',{'class':'v-button v-r'}).appendTo(gContainer);
                        }
			$('.caption',gContainer).remove();
			$('.v-gallery .v-gallery-img-list a').click(function(){
				$('.popup .v-gallery-main-pic img').show();
				$('.v-gallery .v-gallery-img-list a.active').removeClass('active');
				$(this).addClass('active');
				if ($('.v-gallery-popup').length <= 0){
					$('.v-gallery-popup h2').remove();
					$('.v-gallery-popup .description').remove();
					$(this).attr('title') ? $('<h2/>',{'html':$(this).attr('title')}).insertBefore($('.v-gallery-main-pic',gContainer)) : $('.v-gallery-popup h2').remove();
					$(this).attr('rel') ? $('<div/>',{'class':'description','html':$(this).attr('rel')}).appendTo(gContainer) : $('.v-gallery-popup .description').remove();
					popup(gContainer,'v-gallery-popup');
					$('.popup .v-gallery .v-gallery-img-list').jScrollPane({
						verticalDragMinHeight: 21,
						verticalDragMaxHeight: 21
					});
					$('<a/>',{'class':'','html':'<img class="mini" src="'+$('.v-gallery-main-pic a').attr('rel')+'">','title':$('.v-gallery-main-pic a').attr('title'),'href':$('.v-gallery-main-pic a').attr('href')}).insertBefore($('.v-gallery-popup .jspPane a:eq(0)'));
				}
				else{
					$('.v-gallery-popup h2').remove();
					$('.v-gallery-popup .description').remove();
					$(this).attr('title') ? $('<h2/>',{'html':$(this).attr('title')}).insertBefore($('.v-gallery-main-pic',gContainer)) : '';
					$(this).attr('rel') ? $('<div/>',{'class':'description','html':$(this).attr('rel')}).appendTo(gContainer) : '';
					$('.v-gallery-popup').show();
				}
				$('.v-gallery-desc .v-gallery-img-list a').each(function(i){
					if ($('.v-gallery-desc .v-gallery-img-list a:eq('+i+')').hasClass('active')){
						$('.v-gallery-popup .v-gallery-img-list a:eq('+(i+1)+')').addClass('active');
					}
				});
				$('.popup .v-gallery-main-pic img').attr('src',$(this).attr('href'));
				$('.popup .v-gallery-main-pic img').load(function(){
					/*$('.p-inner',$(this).closest('.popup')).css({
						'left':$(window).width()/2 - $('.p-inner',$(this).closest('.popup')).width()/2,'top':$(document).scrollTop() + $(window).height()/2 - $('.p-inner',$(this).closest('.popup')).height()/2
					});*/
					$('.p-lt',$(this).closest('.popup')).height($('.p-inner',$(this).closest('.popup')).height());
					$('.p-rt',$(this).closest('.popup')).height($('.p-inner',$(this).closest('.popup')).height());
				});
				return false;
			});
			$('.v-gallery-desc .v-gallery-main-pic a').click(function(){
				$('.v-gallery-container .active').removeClass('active');
				if ($('.v-gallery-popup').length <= 0){
					$('.v-gallery-popup h2').remove();
					$('.v-gallery-popup .description').remove();
					$(this).attr('title') ? $('<h2/>',{'html':$(this).attr('title')}).insertBefore($('.v-gallery-main-pic',gContainer)) : $('.v-gallery-popup h2').remove();
					/*$(this).attr('rel') ? $('<div/>',{'class':'description','html':$(this).attr('rel')}).appendTo(gContainer) : $('.v-gallery-popup .description').remove();*/
					popup(gContainer,'v-gallery-popup');
					
					$('.popup .v-gallery .v-gallery-img-list').jScrollPane({
						verticalDragMinHeight: 21,
						verticalDragMaxHeight: 21
					});
					$('<a/>',{'class':'active','html':'<img class="mini" src="'+$(this).attr('rel')+'">','title':$(this).attr('title'),'href':$(this).attr('href')}).insertBefore($('.v-gallery-popup .jspPane a:eq(0)'));
				}
				else{
					$('.v-gallery-popup h2').remove();
					$('.v-gallery-popup .description').remove();
					$(this).attr('title') ? $('<h2/>',{'html':$(this).attr('title')}).insertBefore($('.v-gallery-main-pic',gContainer)) : $('.v-gallery-popup h2').remove();
					/*$(this).attr('rel') ? $('<div/>',{'class':'description','html':$(this).attr('rel')}).appendTo(gContainer) : $('.v-gallery-popup .description').remove();*/
					$('.v-gallery-popup').show();
					$('.v-gallery-popup .jspPane a:eq(0)').addClass('active');
				}
				if ($('.v-gallery-popup .v-gallery .jspDrag').length > 0){
					$('.v-gallery-popup .v-gallery .jspDrag').css({'top':$('.v-gallery-desc .v-gallery .jspDrag').position().top});
					$('.v-gallery-popup .v-gallery .jspPane').css({'top':$('.v-gallery-desc .v-gallery .jspPane').position().top});
				}
				$('.v-gallery-desc .v-gallery-img-list a').each(function(i){
					if ($('.v-gallery-desc .v-gallery-img-list a:eq('+(i+1)+')').hasClass('active')){
						$('.v-gallery-popup .v-gallery-img-list a:eq('+(i+1)+')').addClass('active');
					}
				});
				$('.popup .v-gallery-main-pic img').attr('src',$(this).attr('href'));
				$('.popup .v-gallery-main-pic img').load(function(){
					/*$('.p-inner',$(this).closest('.popup')).css({
						'left':$(window).width()/2 - $('.p-inner',$(this).closest('.popup')).width()/2,'top':$(document).scrollTop() + $(window).height()/2 - $('.p-inner',$(this).closest('.popup')).height()/2
					});*/
				});
				return false;
			});
			$('.v-gallery-desc .v-gallery-img-list a').click(function(){
				self.vGalleryPopupCoeff = $('.v-gallery-popup .v-gallery .jspVerticalBar').height()/(55*$('.v-gallery-popup .v-gallery-img-list a').length);
				if ($(this).index() < 9){
					$('.v-gallery-popup .v-gallery .jspPane').css({'top':0});
					$('.v-gallery-popup .v-gallery .jspDrag').css({'top':$('.popup .v-gallery .v-gallery-img-list a.active').position().top*self.vGalleryPopupCoeff});
				}
				else {
					$('.v-gallery-popup .v-gallery .jspPane').css({'top':-$('.popup .v-gallery .v-gallery-img-list a.active').position().top + 460});
					$('.v-gallery-popup .v-gallery .jspDrag').css({'top':$('.popup .v-gallery .v-gallery-img-list a.active').position().top*self.vGalleryPopupCoeff});
				}
				$('.v-gallery-popup .v-gallery-v h2').remove();
				$('.v-gallery-popup .v-gallery-v .description').remove();
				$(this).attr('title') && $(this).attr('title') != '' ? $('<h2/>',{'html':$(this).attr('title')}).insertBefore($('.v-gallery-main-pic',gContainer)) : '';
				$(this).attr('rel') && $(this).attr('rel') != '' ? $('<div/>',{'class':'description','html':$(this).attr('rel')}).appendTo(gContainer) : '';
			});
			$('.popup .v-gallery .v-gallery-img-list a').live('click',function(){
				if ($(this).index() != 0){
					$('.v-gallery-web').html('<div id="v-gallery-web"></div>');
				}
				$('.v-gallery .v-gallery-img-list a.active').removeClass('active');
				$(this).addClass('active');
				if ($(this).closest('.v-gallery-v').length > 0){
					$('.v-gallery-popup h2').remove();
					$('.v-gallery-popup .description').remove();
					$(this).attr('title') && $(this).attr('title') != '' ? $('<h2/>',{'html':$(this).attr('title')}).insertBefore($('.v-gallery-main-pic',gContainer)) : '';
					$(this).attr('rel') && $(this).attr('rel') != '' ? $('<div/>',{'class':'description','html':$(this).attr('rel')}).appendTo(gContainer) : '';
				}
				if ($(this).closest('.v-gallery-h').length > 0){
					$('.v-gallery-popup h2').remove();
					$('.v-gallery-popup .description').remove();
					$(this).attr('title') && $(this).attr('title') != '' ? $('<h2/>',{'html':$(this).attr('title')}).insertBefore($('.v-gallery-main-pic',$(this).closest('.v-gallery-container'))) : '';
					$(this).attr('rel') && $(this).attr('rel') != '' ? $('<div/>',{'class':'description','html':$(this).attr('rel')}).appendTo($(this).closest('.v-gallery-container')) : '';
				}
				if ($('.v-gallery-popup .v-gallery .jspDrag').length > 0){
					if ($(this).index() < 3){
						$('.v-gallery-desc .v-gallery .jspPane').css({'top':0});
						$('.v-gallery-desc .v-gallery .jspDrag').css({'top':($('.popup .v-gallery .v-gallery-img-list a.active').position().top)*self.vGalleryCoeff});
					}
					else {
						$('.v-gallery-desc .v-gallery .jspPane').css({'top':-$('.popup .v-gallery .v-gallery-img-list a.active').position().top + 130});
						$('.v-gallery-desc .v-gallery .jspDrag').css({'top':($('.popup .v-gallery .v-gallery-img-list a.active').position().top)*self.vGalleryCoeff});
					}
				}
				else{
					if ($(this).index() < 3){
						$('.v-gallery-desc .v-gallery .jspPane').css({'top':0});
						$('.v-gallery-desc .v-gallery .jspDrag').css({'top':($('.popup .v-gallery .v-gallery-img-list a.active').position().top)*self.vGalleryCoeff});
					}
					else {
						$('.v-gallery-desc .v-gallery .jspPane').css({'top':-$('.popup .v-gallery .v-gallery-img-list a.active').position().top + 130});
						$('.v-gallery-desc .v-gallery .jspDrag').css({'top':($('.popup .v-gallery .v-gallery-img-list a.active').position().top)*self.vGalleryCoeff});
					}
				}
				$('.v-gallery-popup .v-gallery-img-list a').each(function(i){
					if ($('.v-gallery-popup .v-gallery-img-list a:eq('+i+')').hasClass('active') && (i-1) >= 0){
						$('.v-gallery-desc .v-gallery-img-list a:eq('+(i-1)+')').addClass('active');
					}
				});
				$('.popup .v-gallery-main-pic img').attr('src',$(this).attr('href'));
				return false;
			});
		},
		slideByDates: function(self){
			if (!$('.photos-dates li').length) return;
                        //$('.h-gallery .jspPane').css({'top':''});
                        //alert($('.h-gallery .jspPane').css('top'));
			this.datesCoeff =( $('.h-gallery .jspHorizontalBar').width() - $('.h-gallery .jspHorizontalBar .jspDrag').width() )/($('.h-gallery-slide-area').width()-706);
                        
			$('.photos-dates li').live('click',function(){
				/*if ($(this).is(':last-child')){
					$('.h-gallery .jspPane').animate({
						'left':-$('.h-gallery-slide-area li.'+$(this).attr('class')).position().left
					});
					$('.h-gallery .jspHorizontalBar .jspDrag').css({'left':$('.h-gallery .jspTrack').width() - $('.h-gallery .jspDrag').width()});
				}
				else if ($('.h-gallery-slide-area li.'+$(this).attr('class')).next().length > 0){*/
					$('.h-gallery .jspPane').animate({
						'left':-$('.h-gallery-slide-area li.'+$(this).attr('class')+':eq(0)').position().left
					});
					$('.h-gallery .jspHorizontalBar .jspDrag').css({'left':$('.h-gallery-slide-area li.'+$(this).attr('class')+':eq(0)').position().left*self.datesCoeff});
				//}
			});
		},
		mountEvts: function(){
			this.vGallery.jScrollPane({
				verticalDragMinHeight: 21,
				verticalDragMaxHeight: 21
			});
			if (!$('.h-gallery-slide-area').closest('.content_gallery').length){
                                //alert('1');
//				$('.h-gallery-slide-area').width($('.h-gallery-slide-area li').length * ($('.h-gallery-slide-area li').width()+15));
                                var hWidth = 0;
                                $('.h-gallery-slide-area li').each(function(){hWidth += $(this).width()+15});
                                $('.h-gallery-slide-area').width(hWidth+15);
			}
			else{
                                //alert('2');
				var hWidth = 0;
				$('.h-gallery-slide-area li').each(function(){hWidth += $(this).width()+15});
				$('.h-gallery-slide-area').width(hWidth);
			}
                        //alert($('.h-gallery-slide-area').width());
			this.hGallery.jScrollPane({
				horizontalDragMinWidth: 89,
				horizontalDragMaxWidth: 89
			});
			this.vGalleryCoeff = $('.v-gallery-desc .v-gallery .jspVerticalBar').height()/$('.v-gallery-desc .v-gallery .jspPane').height();
                        $('.h-gallery .jspVerticalBar').remove();
		}
	}
	function popup(bodyHtml,popupClass){
		var html = '<div class="p-substrate"></div>'+
					'<div class="p-inner">'+
						'<b class="p-decor p-lt"></b><b class="p-decor p-rt"></b><b class="p-decor p-lb"></b><b class="p-decor p-rb"></b><b class="p-close"><i class="lt"></i><span>Закрыть</span></b>'+
						'<div class="p-body"></div>'+
					'</div>';
		var p = $('<div/>',{'html':html,'class':'popup '+popupClass}).appendTo($(document.body));
		bodyHtml ? bodyHtml.appendTo($('.p-body',p)) : '';
		$('.p-inner').each(function(){
			if ($(this).closest('.overlay').length <= 0){
                                top_position=$(document).scrollTop() + $(window).height()/2 - $(this).height()/2;
                                if (top_position < 40) {top_position = 40};
				$(this).css({
					'left':$(window).width()/2 - $(this).width()/2,'top':top_position
				});
			}
		});
		
		$('.p-substrate').height($(document).height());
	}
	
	function hidePopup(popup){
		$('.p-close',$(popup)).live('click',function(){
			$(popup).hide();
		});
		$('.p-substrate',$(popup)).live('click',function(){
			$(popup).hide();
		});
	}
	function removePopup(popup){
		if (popup){
			$('.p-close',$(popup)).live('click',function(){
				$(popup).remove();
			});
			$('.p-substrate',$(popup)).live('click',function(){
				$(popup).remove();
			});
		}
		$('.popup.overlay .p-close,#exposeMask').live('click',function(){
			$('.popup.overlay').hide();
			return false;
		});
	}
	function sortingTable(){
		var sorting = [[1,0]];
		$("table.sorting:not(.s-head)").tablesorter(); 
		$("table.s-head .sort").click(function() {
			if ($(this).hasClass('s-bottom')){
				sorting = [[$(this).index(),1]];
				$(this).addClass('s-top').removeClass('s-bottom'); 
			}
			else if ($(this).hasClass('s-top')){
				sorting = [[$(this).index(),0]];
				$(this).addClass('s-bottom').removeClass('s-top'); 
			}
			else{
				sorting = [[$(this).index(),0]];
				$(this).addClass('s-top'); 
			}
			$("table.sorting:not(.s-head)").trigger("sorton",[sorting]); 
			$("table.s-head th").removeClass('sorted');
			$(this).addClass('sorted');
			return false; 
		}); 
		$("table.sorting:not(.s-head)").trigger("sorton",[sorting]); 
	}
	function cSelect(){
		if ($('.toCSelect').length <= 0) return;
		
		$('.toCSelect').each(function(){
			var option = '<ul class="options">';
			$('option',$(this)).each(function(){
				if ($(this).is(':selected'))
					option += '<li selected="selected" data-rel="'+$(this).attr('rel')+'" data-value="'+$(this).val()+'" class="option">'+$(this).text()+'</li>'
				else
					option += '<li data-rel="'+$(this).attr('rel')+'" data-value="'+$(this).val()+'" class="option">'+$(this).text()+'</li>'
			});
			option += '</ul>';
			var html = '<div class="currentValue">'+$('option:selected',$(this)).text()+'</div>'+
							'<input type="hidden" name="'+$(this).attr('name')+'" value="'+$('option:selected',$(this)).val()+'">'+option;
			$('<div/>',{'class':'cSelect '+$(this).attr('class'),'html':html}).insertBefore($(this));
			$(this).remove();
		});
		
		$('.cSelect').each(function(){
			var cSelect = $(this),bodyClick = '';
			$('.currentValue',$(this)).live('click',function(){
				$('.cSelect').removeClass('cSelect-open');
				cSelect.toggleClass('cSelect-open');
				$(document.body).bind('click',bodyClick = function(e){
					if ($(e.target).closest('.cSelect-open').length <= 0){
						cSelect.removeClass('cSelect-open');
						$(document.body).unbind('click',bodyClick);
					}
				});
			});
			if ($('.option[selected="selected"]',$(this)).length <= 0){
				$('.option:eq(0)',$(this)).attr('selected','selected');
			}
			$('.option',$(this)).live('click',function(){
				$('.currentValue',cSelect).text($(this).text());
				$('input[type="hidden"]',cSelect).attr('value',$(this).attr('data-value'));
				cSelect.removeClass('cSelect-open');
				$('.option',cSelect).removeAttr('selected');
				$(this).attr('selected','selected');
			});
			$('.currentValue',$(this)).text($('.option:eq(0)',$(this)).text());
			$('input[type="hidden"]',cSelect).attr('value',$('.option:eq(0)',cSelect).attr('data-value'));
			$('.option[selected]',$(this)).each(function(){
				$('.currentValue',cSelect).text($(this).text());
				$('input[type="hidden"]',cSelect).attr('value',$(this).attr('data-value'));
			});
		});
	}
	function flatEvts(){
		$('.flat-description .closeForm').live('click',function(){
			$('.flat-description .request').hide(300);
			$('.flat-description .toOrder').show();
			return false;
		});
		$('.flat-description .toOrder').live('click',function(){
			$('.flat-description .request').show(300);
			$(this).hide();
			return false;
		});
		$('.b-sections__section_roof').each(function(){
			$('<div/>',{'class':'before'}).appendTo($(this)).width($(this).width()-20);
		});
                $('.b-sections__section_roof_built').each(function(){
                        $('<div/>',{'class':'before'}).appendTo($(this)).width($(this).width()-20);
                });

	}
	
	function filtering(self,priceFrom,priceTo,squareFrom,squareTo,floorFrom,floorTo,numRooms,elem,objStatus, perfomance_checked_l){
		var current_price = Number($('input[name="price"]',self).val());
		
		var checkPriceFrom = current_price >= priceFrom;
		var checkPriceTo = current_price <= priceTo;
		var current_square = Number($('input[name="square_from"]',self).val());
		var checkSquareFrom =  current_square <= squareTo;
                var current_square = Number($('input[name="square_to"]',self).val());
		var checkSquareTo = current_square >= squareFrom;
                var current_floor_from = Number($('input[name="floor_from"]',self).val());
                if (floorFrom == 0){
                    var checkFloorFrom = true;
                } else {
                    var checkFloorFrom = current_floor_from <= floorTo;
                }
                var current_floor_to = Number($('input[name="floor_to"]',self).val());
                if (floorTo == 100){
                    checkFloorTo = true;
                } else {
                    var checkFloorTo = current_floor_to >= floorFrom;
                }
		var checkRoomsCount = false;
		var checkPerfomance = false;
		var checkObjectStatus = false;
		var current_status = $('.object_status',self).attr('name');
		var rooms_count = $('input[name="rooms_count"]',self).val() != '' ? eval('('+$('input[name="rooms_count"]',self).val()+')') : [];
	        if (numRooms.length){	
		  for (var i=0;i<numRooms.length;i++){
			  for (var j=0;j<rooms_count.length;j++){
				if (numRooms[i] == rooms_count[j]){
					checkRoomsCount = true;
				}
		   	  }
		  }
		} else {
                   checkRoomsCount = true;
                }
		var perfomance = eval('('+$('input[name="perfomance"]',self).val()+')');
		if (perfomance_checked_l > 0){
			for (var i = 0;i<perfomance.length;i++){
				if ($('.obj-filter input[name="'+perfomance[i]+'"]').is(':checked')){
					checkPerfomance = true;
				}
			}
		}
		else checkPerfomance = true;
	        //if (objStatus.length >0){
                //alert(objStatus);
		for (var i = 0;i<objStatus.length;i++){
			if (objStatus[i] == current_status) {
				checkObjectStatus = true;
		   }
		}
                //} else checkObjectStatus = true;
                var checkedPrice = checkPriceFrom && checkPriceTo;
                var checkedSquare = checkSquareFrom && checkSquareTo;
                var checkedFloor = checkFloorTo && checkFloorFrom;
	        var checkStatus = checkedPrice && checkedSquare && checkedFloor && checkRoomsCount && checkPerfomance && checkObjectStatus;	
		if (checkStatus){
			self.closest(elem).show();
			if ($('table tr:visible',self.closest('.objects-item')).length != 0){
				self.closest('.objects-item').show();
			}
		}
		else{
			self.closest(elem).hide();
			if (!$('tr:visible',$(self).closest('.corpuses-list')).length){
				$(self).closest('.objects-item').hide()
			}
		}
		
	}
	function filterObj(){
		$('.obj-filter input[type="submit"]').click(function(){
			var $thisNumRooms = [];
			var priceFrom = Number($('.obj-filter .price .from').val()) || 0;
			var priceTo = Number($('.obj-filter .price .to').val()) || 9000000;
			var squareFrom = Number($('.obj-filter .square .from').val()) || 0;
			var squareTo = Number($('.obj-filter .square .to').val()) || 1000000;
                        var floorFrom = Number($('.obj-filter .floor .from').val()) || 0;
                        var floorTo = Number($('.obj-filter .floor .to').val()) || 100;
                        if (priceFrom > priceTo){
                            priceFrom = priceTo;
                            $('.obj-filter .price .from').val(priceFrom);
                        }
                        if (squareFrom > squareTo){
                            squareFrom = squareTo;
                            $('.obj-filter .square .from').val(squareFrom);
                        }
                        if (floorFrom > floorTo){
                            floorFrom = floorTo;
                            $('.obj-filter .floor .from').val(floorFrom);
                        }


			var objStatus = [];
			var statusCheckedCount = Number($('.obj-filter .object_status:checked').length);
			if (!statusCheckedCount){
				$('.obj-filter .object_status').each(function(){
					objStatus.push($(this).attr('value'));
				});
			}
			else{
				$('.obj-filter .object_status:checked').each(function(){
					objStatus.push($(this).attr('value'));
				});
			}
			
			$('.flats-num input[type="checkbox"]').each(function(){
				if ($(this).is(':checked')) $thisNumRooms.push($(this).val());
			});
			var perfomance_checked_l = Number($('.obj-filter .perfomance:checked').length);
			if (priceFrom != 0 || priceTo != 0){
				$('ul.objects-list:visible .objects-item').each(function(){
					if ($('td.price',$(this)).length > 0){
						$('td.price',$(this)).each(function(){
		filtering($(this),priceFrom,priceTo,squareFrom,squareTo,floorFrom,floorTo,$thisNumRooms,'tr',objStatus, perfomance_checked_l);
						});
					}
					else{
						$('div.price',$(this)).each(function(){
							filtering($(this),priceFrom,priceTo,squareFrom,squareTo,floorFrom,floorTo,$thisNumRooms,'.objects-item',objStatus, perfomance_checked_l);
						});
					}
				});
				$('ul.objects-list:visible .objects-item').each(function(){
					if ($('td.price',$(this)).length > 0){
						div_info = $(this).find('div.info');
                                                        icon_obj = div_info.find('div.icons img')[3];
	//													console.log(statusCheckedCount);
                                                        if (statusCheckedCount){
                                                          $('.obj-filter .object_status:checked').each(function(){
                                                          //    alert(icon_obj.longdesc);
	//													  console.log('Start find icon');
                                                              if (icon_obj.longdesc == undefined){
                                                                icon_obj.longdesc = icon_obj.src;
                                                                
                                                              }
                                                              var chk = $(this).attr('value');
                                                              icon_obj.src = '/icons/'+chk+'.png';
                                                              if (chk == 'underConstruction'){
                                                                icon_obj.title = 'идет строительство';
                                                              }
                                                              if (chk == 'built'){
                                                                icon_obj.title = 'дом построен';
                                                              }
                                                               if (chk == 'occupy'){
                                                                icon_obj.title = 'идет заселение';
                                                              }

                                                              
                                                           });
                                                        } else {
															if (icon_obj.longdesc != undefined){
                                                              icon_obj.src = icon_obj.longdesc;
                                                              icon_obj.title = icon_obj.alt;
														    }
                                                        } 
//						$('td.price',$(this)).each(function(){
//	                        var corps_count = $('.corpuses-list tr:visible',$(this).closest('.objects-item')).length;
                            corps_count = Number($('.corpuses-list tr:visible',$(this).closest('.objects-item')).length);
							// console.log(corps_count);
							corps_name = div_info.find('.corpuses b')
                            // console.log(corps_name.length);
							if (corps_name.length)
							{
							    
						    	if (corps_count >= 5){
								  corps_name.html(corps_count + ' корпусов, ');
                               
							    } else if (1< corps_count && corps_count < 5){
								  corps_name.html(corps_count + ' корпуса, ');
                                
							  } else if (corps_count == 1){
								  corps_name.html('1 корпус, ');
                                
							  } 
							}
							else if (corps_count == 0){
								$(this).hide();                              
							}
//						});
					}
				});
			}
			if ($('.googleMapView-container').height() > 0){
                mapFiltering();
			}else {
				numeralObjectList();
		    }
			if (!$('.objects-item:visible').length){
				if (!$('.emptySearch').length){
					$('<div/>',{'html':'Объектов удовлетворяющих вашим условиям не найдено.','class':'emptySearch'}).insertBefore($('.news-container'));
				}
			}
			else $('.emptySearch').remove();
			if (!$('.googleMapView-container').height()){
				unNumeralObjectList();
			}
			/*$('.googleMapView-container').height(500);
			$('.show-map').text('Скрыть карту');*/
		});
		
	}
	
	function sortObjects(){
		$('.sort li a:not(.show-map)').bind('click',function(){
			$('.sort li').removeClass('active rc4');
                        $('.sort li').attr('id', '');
                        active_el = $(this).closest('li');
                        var ua = $.browser;
                        if (!ua.opera) {

			    active_el.addClass('active rc4');
                        } else { active_el.addClass('active'); }
                        
                        active_el.attr('id', 'forrcon');
			$('.objects-list').hide();
			$('.objects-list.'+$(this).attr('rel')).show();
			mapFiltering();
                        $('.obj-filter input[type="submit"]').trigger('click');
                        if (!ua.opera) {
                            var rounded = document.getElementById('forrcon');
                            rocon.update(rounded);
                        }
                        //filterObj();
			//numeralObjectList();
			return false;
		});
	}
	
	function mapFiltering(){
		$('.googleMapView').html('').removeClass('googleMapActive');
		var gmapData = '';
		$('.objects-item:visible').each(function(i){
			if ($('input[name="mapdata"]',this).val()){
			var mapdata = eval('('+$('input[name="mapdata"]',this).val()+')');
			gmapData += ' <dt class="title">'+
							'<img src="/marker.png" alt="Building'+(i+1)+'" width="16" height="16" class="marker" />'+
							'<a href="'+mapdata.title.link.href+'">'+mapdata.title.link.text+'</a>'+
						 '</dt>'+
						 '<dd class="geo">'+
							'<span class="latitude">'+mapdata.geo.latitude+'</span>'+
							'<span class="longitude">'+mapdata.geo.longitude+'</span>'+
						 ' </dd>';
			}
		});
		$('<dl/>',{'html':gmapData}).appendTo($('.googleMapView'));
		mapsGoogleMaps.init();
	}
	function cottageRequest(){
		$('.cottage-description .request').hide();
		$('.cottage-description .toOrder').live('click',function(){
			$('.request',$(this).closest('.cottage-description')).show();
			$(this).hide();
		});
		$('.cottage-description .request .closeForm').live('click',function(){
			$(this).closest('.request').hide();
			$('.toOrder',$(this).closest('.cottage-description')).show();
			return false;
		});
	}
	function filterRedirect(){
		if (!$('.b-filter').length) return;
		var dop = ($('.b-filter .cSelect.type .option[selected]').length ? $('.b-filter .cSelect.type .option[selected]').attr('data-rel').replace(/.*\?/gi,'') : $('.b-filter .cSelect.type .option:eq(0)').attr('data-rel').replace(/.*\?/gi,''));
		var replaceUrl = $('.b-filter .cSelect.region .option[selected]').attr('data-rel') + '?' + dop;
		$('.b-filter .option[data-rel]').live('click',function(){
			if ($(this).closest('.region').length){
				var s = ($('.b-filter .cSelect.type .option[selected]').length ? $('.b-filter .cSelect.type .option[selected]').attr('data-rel').replace(/.*\?/gi,'') : $('.b-filter .cSelect.type .option:eq(0)').attr('data-rel').replace(/.*\?/gi,''));
				replaceUrl = $(this).attr('data-rel') + '?' + s;
			}
			else{
				replaceUrl = $(this).attr('data-rel');
			}
		});
		$('.b-filter input[type="button"]').bind('click',function(){
			window.location.replace(replaceUrl);
		})
	}
	function contentGallery(){
		$('.content_gallery .bigImg').show().css({'left':$('.content_gallery .h-gallery').width()/2 - $('.content_gallery .bigImg').width()/2});
		$('.content_gallery .bigImg').load(function(){
			$(this).show().css({'left':$(this).parent().width()/2 - $(this).width()/2});
		});
		$('.h-gallery-slide-area li').bind('click',function(){
			$('.content_gallery .bigImg').hide()
				.attr('src',$('img',this).attr('rel'));
			$('.content_gallery .bigImg').load(function(){$(this).css({'left':$('.content_gallery .h-gallery').width()/2 - $(this).width()/2});});
				
		});
	}
	function newsArchive(){
		$('.archive:eq(1)').addClass('down');
		$('<div/>',{'class':'listingBar fListingBar'}).appendTo($('body')).hide();
		$('.archive.down').clone().appendTo($('.fListingBar'));
		$('.fListingBar .archive.down').removeClass('down');
		//$('.archive.down .years').remove();
		$('.archive-l').bind('click',function(){
			$(this).toggleClass('open-archive');
			if ($(this).closest('.archive.down').length){
				$(this).toggle();
				$('.fListingBar').show();
				$('.fListingBar').css({
					'left':$('.archive.down').position().left + $('#portal-columns').position().left,
					'top':$('.archive.down').position().top + $('#portal-columns').position().top
				});
				$('.fListingBar .archive-l').addClass('open-archive');
				$('.fListingBar .years').toggle();
			}
			else{
				$('.years',$(this).closest('.archive')).toggle();
			}
			return false;
		});
		var hide = '';
		$('body').bind('click',hide = function(e){
			if (!$(e.target).closest('.archive').length){
				$('.open-archive').removeClass('open-archive');
				$('.archive .years').hide();
			}
		});
		var coeff = $('.content_gallery .jspHorizontalBar').width() / ($('.content_gallery .h-gallery-slide-area').width() - $('.content_gallery .jspPane').width());
		var maxScroll = $('.content_gallery .h-gallery-slide-area').width() - $('.content_gallery .jspPane').width();
		$('.newsImageContainer a').bind('click',function(){
                    //    alert($('img',this).attr('id'));
			var left = ($('.content_gallery li.'+$('img',this).attr('id')).position().left > maxScroll ? maxScroll : $('.content_gallery li.'+$('img',this).attr('id')).position().left)
			var leftS = ($('.content_gallery li.'+$('img',this).attr('id')).position().left > maxScroll ? 617 : $('.content_gallery li.'+$('img',this).attr('id')).position().left * coeff)
                        $('.content_gallery li.'+$('img',this).attr('id')).click();
			$('.content_gallery .jspPane').animate({'left':-left});
			$('.content_gallery .jspDrag').animate({'left':leftS});
                        var new_position = $('.content_gallery').offset();
                        window.scrollTo(new_position.left,new_position.top);
			return false;
		});
	}
	function fixie(){
		if (/MSIE 6/.test(navigator.userAgent)){
			$('#portal-header #portal-globalnav li').hover(function(){$(this).addClass('hover')})
		}
		if (/MSIE 7/.test(navigator.userAgent)){
			/*var width = 0;
			$('#portal-header #portal-globalnav li.dropdown ul li').each(function(){
				$(this).width() > width ? width = $(this).width() : '';
			});
			$('#portal-header #portal-globalnav li.dropdown ul li').width(width);
			width = 0;
			$('#portal-header #portal-globalnav li.dropdown ul ul li').each(function(){
				$(this).width() > width ? width = $(this).width() : '';
			});
			$('#portal-header #portal-globalnav li.dropdown ul ul li').width(width);*/
		}
	}
	function gallSWF(img_url ,stream, newcam){
                if (newcam) {
		  var flashvars = {server:stream,};
		  var params = { allowfullscreen:'false', allowscriptaccess:'always' };
		  var attributes = { id:'player1', name:'player1' };
		
		  swfobject.embedSWF('/BasicPlayer.swf','v-gallery-web','704','480','9.0.115','false',
		   flashvars, params, attributes);
		
		
		  function stop_play(){
			player1.sendEvent('STOP');
			window.close();
		  }
		} else {
                  var flashvars = {image:img_url, start:'1',file:stream,autostart:'true',controlbar:'none'};
                  var params = { allowfullscreen:'false', allowscriptaccess:'always' };
                  var attributes = { id:'player1', name:'player1' };

                  swfobject.embedSWF('/jwplayer/player.swf','v-gallery-web','704','480','9.0.115','false',
                   flashvars, params, attributes);


                  function stop_play(){
                        player1.sendEvent('STOP');
                        window.close();
                  }
 
                }
		//intID = window.setInterval(stop_play, 1000*60*2);
	}
	function callManager(){
		$('#parent-fieldname-text a').filter('[href]').each(function(){
			if ($(this).attr('href').match(/contact-form/gi)){
				$(this).addClass('managerCallOrder');
			}
		});
	}
	function showHint(){
		var bodyHide = '';
		$('.financial-indicators .hint span').bind('click',function(){
			$('.h-text',$(this).closest('.hint')).show();
			$('body').bind('click',bodyHide = function(e){
				if (!$(e.target).closest('.hint').length)
					$('.hint .h-text').hide();
			});
		});
		$('.financial-indicators .h-text .close').bind('click',function(){
			$(this).closest('.h-text').hide()
		});
	}
	function tableIpotekaHead(){
		if (!$('.t-ipoteka').length) return;
		
		if ($('#portal-column-one').length){
			$('<div/>',{'class':'t-ipoteka-header','html':'<table class="t-ipoteka">'+$('.t-ipoteka thead').html()+'</table>'}).appendTo($('body'));
		}
		else $('<div/>',{'class':'t-ipoteka-header t-ipoteka-header-w','html':'<table class="t-ipoteka">'+$('.t-ipoteka thead').html()+'</table>'}).appendTo($('body'));
		/*$('.t-ipoteka-header th').each(function(i){
			$(this).width($('#content .t-ipoteka th:eq('+i+')').width());
		});*/
		$(window).load(function(e){
			if ($(this).scrollTop() > ($('#content .t-ipoteka').position().top + 150)) $('.t-ipoteka-header').show()
			else $('.t-ipoteka-header').hide()
		});
		if ($.browser.msie){
			$(window).scroll(function(e){
				if ($(this).scrollTop() > ($('#content .t-ipoteka').position().top + 150)) $('.t-ipoteka-header').show()
				else $('.t-ipoteka-header').hide()
			});
		}
		else{
			$(document).scroll(function(e){
				if ($(this).scrollTop() > ($('#content .t-ipoteka').position().top + 150)) $('.t-ipoteka-header').show()
				else $('.t-ipoteka-header').hide()
			});
		}
	}
	function checkEmptyLeftCol(){
		if ($.trim($('#portal-column-one').text()) == '') $('#portal-column-one').remove()
	}
	function atrb_crit(){
		if (!$('#atrb_crit__path_ATPathCriterion_value').length) return;
		$('#atrb_crit__path_ATPathCriterion_value').appendTo($('body'));
	}
	function showMapOfObjects(){
		$('.show-map').show();
		$('.show-map').click(function(){
			$('.googleMapView-container').height($('.googleMapView-container').height() == 0 ? 500 : 0);
			$(this).text($(this).text() == 'Показать на карте' ? 'Скрыть карту' : 'Показать на карте');
			mapFiltering();
			if ($('.googleMapView-container').height()){
				numeralObjectList();
			}
			else{
				unNumeralObjectList();
			}
			return false;
		});
	}
	function flatRequest(){
		var chNames = ['sender_lastname','sender_firstname'];
		$('.flat-request').live('submit',function(){
												  
			for (var i=0;i<chNames.length;i++){
				if ($('input[name="'+chNames[i]+'"]',this).val() == ''){
					$('input[name="'+chNames[i]+'"]',this).addClass('error');
				}
				else{
					$('input[name="'+chNames[i]+'"]',this).removeClass('error');
				}
			}
			
$('.phone input',this).each(function() {
tmp = $(this).val();
tmp = tmp.replace(/[^0-9]/g, '');
$(this).val(tmp.replace(/[^0-9]/g, ''));
tmp = $(this).val();
if (tmp.length == 11){
    $(this).val(tmp.substring(1));
};
tmp = $(this).val();
if (tmp.length != 10){
    $(this).addClass('error');
} else {
    $(this).removeClass('error');
};
});
//			if ($('.phone input',this).val() == ''){
//				$('.phone input',this).addClass('error');
//			}
//			else{
//				$('.phone input',this).removeClass('error');
//			}
			
			if ($('.error',this).length){
				return false;
			}
			else{
				return true;
			}
		});
	}
	function initAll(){
		fixie();
		//secE();
		myChartId();
		flatRequest();
		showMapOfObjects();
		filterObj();
                //startGraph();
		atrb_crit();
		checkEmptyLeftCol();
		showHint();
		callManager();
		cottageRequest();
		openSub();
		sortObjects();
		sectionsEvts();
		cSelect();
		flatEvts();
		sortingTable();
		new sValidate().init();
		removePopup();
		filterRedirect();
                removeRocon();
                setbreadcrumbs();
	}

	$(document).ready(function(){
		initAll();
	});

	$(window).load(function(){
                if ($(".v-gallery-container").length > 0 || $(".h-gallery-container").length > 0){
		  new gallery().init();
		  contentGallery();
                }
		newsArchive();
		tableIpotekaHead();
	});

})(jQuery)

function getUrlVars()
{
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++)
    {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
    }
    return vars;
}
function setbreadcrumbs(){
    UrlVars = getUrlVars();
    var rtypes = new Array();
    rtypes['flats'] = 'Квартиры';
    rtypes['cars'] = 'Машиноместа';
    rtypes['cottages'] = 'Коттеджи и таунхаусы';
    rtypes['commercial'] = 'Коммерческая недвижимость';
    var stypes = new Array();
    stypes['realisation'] = 'В продаже';
    stypes['plans'] = 'Планы';
    stypes['progress'] = 'Реализованные';
    if (UrlVars.length > 0){
        if ("type" in UrlVars){
            //alert(UrlVars["type"]);
            
            $("div#portal-breadcrumbs ul li#breadcrumbs-2 a").first().text(rtypes[UrlVars["type"]]);
            if (UrlVars["type"] != 'flats'){
                $("div#portal-breadcrumbs ul li#breadcrumbs-2 a").first().attr("href", $("div#portal-breadcrumbs ul li#breadcrumbs-2 a").first().attr("href")+'/'+UrlVars["type"]);
            }
        }
        if ("status" in UrlVars){
            //alert(UrlVars["status"]);
            $("div#portal-breadcrumbs ul li#breadcrumbs-3 a").first().text(stypes[UrlVars["status"]]);
            if (UrlVars["status"] == 'realisation'){
              $("div#portal-breadcrumbs ul li#breadcrumbs-3 a").first().attr("href", $("div#portal-breadcrumbs ul li#breadcrumbs-2 a").first().attr("href"));
            } else {
              $("div#portal-breadcrumbs ul li#breadcrumbs-3 a").first().attr("href", $("div#portal-breadcrumbs ul li#breadcrumbs-2 a").first().attr("href")+'/'+UrlVars["status"]);
            }
            $("div#portal-breadcrumbs ul li#breadcrumbs-3 ul.buildings a").each(function(){
             url_el = this.href.split('/');
             lst = url_el[url_el.length-1];
             if ( lst == 'progress' || lst == 'plans' ) {
                $(this).attr("href", $("div#portal-breadcrumbs ul li#breadcrumbs-2 a").first().attr("href")+'/'+lst);
             } else {
                $(this).attr("href", $("div#portal-breadcrumbs ul li#breadcrumbs-2 a").first().attr("href"));
             }
            })
        }
        if ("status" in UrlVars){
        dataurl = window.location.href.slice(0, window.location.href.indexOf('?')) + '/breadcr?search_types=' + UrlVars["type"] + '&search_status='+UrlVars["status"];
        //alert(dataurl);
        $.get(dataurl, function(data){
            //alert(data);
            $("div#portal-breadcrumbs ul li#breadcrumbs-4").first().html(data);
            //$("div#portal-breadcrumbs ul").first().append(data);
        })
      }
    }
}
function removeRocon(){
    var ua = $.browser;
    if (ua.opera) {
       $('li.rc4').each(function() {
//          alert('remove rocon');
          $(this).removeClass('rc4');
       }
       )
          $('li.rc5').each(function() {
//          alert('remove rocon');
          $(this).removeClass('rc5');
       }
       )

    }
}
function startGraph(){
            if (!$('table.financial-indicators').length) return;
        var data = '/investors/financial-highlights/getChartData?type=bar&types=';
        var data1 = '/investors/financial-highlights/getChartData?type=lines&types=';
        var data2 = '/investors/financial-highlights/getChartData?type=bar&values=meters&types=';
        var data3 = '/investors/financial-highlights/getChartData?type=lines&values=meters&types=';
        var checks = [];
                $('table.financial-indicators input[type="checkbox"]:checked').each(function(){
                        checks.push($(this).val());
                });
        var graph_id = 'ChartRubBar';
        var dataurl = data.concat(checks);
        $.get(dataurl, function(data){
                        var count = 0;
                        $(data).find("dataset").each(function() {
                          count++;
                        })
                        //alert(count);
                        if (count > 0){
                            //alert(count);
                            var myChart = new FusionCharts( "/charts/FCF_MSColumn3D.swf",
      "ChartRubBar", "600", "300", "1", "1" );
                            myChart.setDataURL(escape(dataurl));
                             myChart.render("Cont" + graph_id);
                        } else {
                            $('div#Cont'+graph_id).hide();
                        }

                      });

       graph_id = 'ChartRubLines';
       dataurl = data1.concat(checks);
               $.get(dataurl, function(data){
                        var count = 0;
                        $(data).find("dataset").each(function() {
                          count++;
                        })
                        if (count > 0){
                            var myChart1 = new FusionCharts( "/charts/FCF_MSLine.swf",
      "ChartRubBar", "600", "300", "1", "1" );
                            myChart1.setDataURL(escape(dataurl));
                             myChart1.render("Cont" + graph_id);
                        } else {
                            $('div#Cont'+graph_id).hide();
                        }

                      });

        
     

}

function myChartId(){
	if (!$('table.financial-indicators').length) return;
        //alert('1');
	//var data = '/investors/financial-highlights/getChartData?types=', checks = [];
        var rurl = window.location.toString();
        if (rurl.indexOf('dollars') > 0){
            var data0 = '/investors/financial-highlights/getChartData?currency=dollars&type=bar&types=';
            var data1 = '/investors/financial-highlights/getChartData?currency=dollars&type=lines&types=';
            var data2 = '/investors/financial-highlights/getChartData?currency=dollars&type=bar&values=met&types=';
            var data3 = '/investors/financial-highlights/getChartData?currency=dollars&type=lines&values=met&types=';
            var data4 = '/investors/financial-highlights/getChartData?currency=dollars&type=bar&values=metrub&types=';
            var data5 = '/investors/financial-highlights/getChartData?currency=dollars&type=lines&values=metrub&types=';
            var data5 = '/investors/financial-highlights/getChartData?currency=dollars&type=bar&values=koeff&types=';
            var data6 = '/investors/financial-highlights/getChartData?currency=dollars&type=lines&values=koeff&types=';

        } else {
            var data0 = '/investors/financial-highlights/getChartData?type=bar&types=';
            var data1 = '/investors/financial-highlights/getChartData?type=lines&types=';
            var data2 = '/investors/financial-highlights/getChartData?type=bar&values=met&types=';
            var data3 = '/investors/financial-highlights/getChartData?type=lines&values=met&types=';
            var data4 = '/investors/financial-highlights/getChartData?type=bar&values=metrub&types=';
            var data5 = '/investors/financial-highlights/getChartData?type=lines&values=metrub&types=';
            var data6 = '/investors/financial-highlights/getChartData?type=bar&values=koeff&types=';
            var data7 = '/investors/financial-highlights/getChartData?type=lines&values=koeff&types=';

        }
        //alert(data);
        var checks = [];
	$('table.financial-indicators input[type="checkbox"]').change(function(){
		checks = [];
                //alert($(this).attr('alt'));
		$('table.financial-indicators input[type="checkbox"]:checked').each(function(){			
			checks.push($(this).val());
		});
                var graph_id = $(this).attr('alt');
                data = data0
                if (graph_id == 'ChartRubBar'){ data = data0 };
                if (graph_id == 'ChartRubLines'){ data = data1 };
                if (graph_id == 'ChartMetBar'){ data = data2 };
                if (graph_id == 'ChartMetLines'){ data = data3 };
                if (graph_id == 'ChartMetrubBar'){ data = data4 };
		if (graph_id == 'ChartMetrubLines'){ data = data5 };
                if (graph_id == 'ChartKoeffBar'){ data = data6 };
                if (graph_id == 'ChartKoeffLines'){ data = data7 };
                dataurl = data.concat(checks);
                //alert(dataurl);
		//myChart.setDataURL(data);
                if ($('div#Cont'+graph_id).is(":visible")) {
                $.get(dataurl, function(data){
                        //alert(data);
                        var count = 0;
                        $(data).find("dataset").each(function() {
                          count++;
                        })
                        //alert(count);
                        if (count > 0){ 
                            //alert(graph_id);
                            try {
                              var str = (new XMLSerializer()).serializeToString(data);
                            } catch (e) {
                              try {
                                var str = data.xml;
                              } catch (e) {
                                var str = '';
                              }
                            }

                            //alert(str);
                            //$('div#Cont'+graph_id).show();
                            updateChartXML(graph_id, str);
                        } else {
                            //alert($('div#Cont'+graph_id).text());
                            //alert($(graph_id).attr('flashvars'));
                            $('div#Cont'+graph_id).hide();
                        }
                        
                      });
                 } else {
                     $('div#Cont'+graph_id).empty();
                     $('div#Cont'+graph_id).show();
                     var chartUrl = "/charts/FCF_MSColumn3D.swf";
                     if (graph_id.indexOf('Lines') > 0){chartUrl = "/charts/FCF_MSLine.swf" }
                     
                     var myChart = new FusionCharts( chartUrl,
                     graph_id, "600", "300", "1", "1" );
                     myChart.setDataURL(escape(dataurl));
//                     alert(dataurl);
                     myChart.render("Cont"+graph_id);


                 }
//                dataurl = data1.concat(checks);
                //alert(dataurl);
//                $.get(dataurl, function(data){
                        //alert(data);
//                        var str = (new XMLSerializer()).serializeToString(data);
                        //   alert(str);
//                        updateChartXML("ChartRubLines", str);
//                      });

		//myChart.render("chartContainer");
	});
}
function sectionsEvts(){
        var sections_length = Number($('.b-sections').length);
	if (sections_length){
		var width = 0;
		$('.b-sections .b-sections__section').each(function(){
			width += $(this).width() + 25;
		});
		$('.b-sections .scrollPane').width(width);
		$('.b-sections ').jScrollPane({
			horizontalDragMinWidth: 89,
			horizontalDragMaxWidth: 89
		});
		$('.b-sections__section_title').each(function(){
			$(this).width($(this).closest('ul').width());
		});
		var maxHeight = 0;
		$('.b-sections-plans__section').each(function(){
			if ($(this).next()){
				if ($(this).height() > maxHeight){
					maxHeight = $(this).height();
				}
			}
		});
		$('.b-sections-plans__section').height(maxHeight);
	}
	
}
$(function(){
	(function(){
		$('.p-furnish .small-img img').live('click',function(){
			$('.p-furnish .big-img').attr('src',$(this).attr('rel'));
		});
	}())
});

