(function($){
	//	selected apartments close button
	$(function(){
		$('.apartments-selected').find('tr').eq(1).find('a.addr').mouseover(function(){
			var
				button = $(this).next().removeClass('hidden'),
				timer = button.data('timer');
			
			if(timer) clearTimeout(timer);
		}).mouseout(function(){
			var
				button = $(this).next(),
				timer = setTimeout(function(){
					button.addClass('hidden');
				}, 500);
			button.data('timer', timer);
		}).next().mouseover(function(){
			var timer = $(this).data('timer');
			if(timer) clearTimeout(timer);
		}).mouseout(function(){
			var
				button = $(this),
				timer = setTimeout(function(){
					button.addClass('hidden');
				}, 500);
			button.data('timer', timer);	
		}).click(function(){
			var
				scrolling = $('#apartments-selected-scroller'),
				button = $(this),
				td = button.closest('td'),
				tds = td.parent().children(),
				trs = td.parent().parent().children(),
				index = tds.index(td[0]);
			trs.each(function(){
				$(this).children().eq(index).remove();
			});
			
			scrolling.data('update')();
			
			return false;
		});
	})

	// custom checkbox
	$(function(){
		$('.checkbox-1').each(function(){
			var
				$this = $(this).hide(),
				cb = $('<div class="checkbox-1-custom" />').prependTo($this.parent());
				if($this.is(':checked')){
					cb.addClass('checkbox-1-custom-checked');
				}else{
					cb.removeClass('checkbox-1-custom-checked');
				}
			
			$this.click(function(){
				cb.toggleClass('checkbox-1-custom-checked');
			});
			
			cb.click(function(){
				$this.click();
			});
		});
	});
	
	//	selected apartments
	$(function(){
		var
			scrolling = $('#apartments-selected-scroller');
		if(!scrolling.length) return;
		var
			proxy = scrolling.find('.scroll-dd-proxy'),
			bar = proxy.prev(),
			apartments = $('.apartments-selected'),
			wrapper = apartments.parent().parent(),
			renderScroller = function(){
				var
					wrapperWidth = wrapper.width(),
					tableWidth = apartments.width(),
					scrollingWidth = scrolling.width(),
					tableLeft = parseInt(apartments.css('left')) || 0;
				
				setTimeout(function(){
					bar.add(proxy).width(Math.min(wrapperWidth * scrollingWidth / tableWidth, scrollingWidth)).css('left', -tableLeft * scrollingWidth / tableWidth);
				}, 20);
			},
			initDD = function(){
				if(proxy.data('dd'))
					proxy.dd('destroy');
				proxy.dd({
					position: 'absolute',
					region: scrolling,
					axis: 'x'
				}).bind('dd-drag-after', function(){
					var left = proxy.css('left');
					bar.css('left', left);
					
					var
						wrapperWidth = wrapper.width(),
						tableWidth = apartments.width(),
						scrollingWidth = scrolling.width(),
						tableLeft = parseInt(apartments.css('left')) || 0;
					
					apartments.css('left', -tableWidth * parseInt(left) / scrollingWidth);
				});
			};
		
		renderScroller();
		initDD();
		scrollingUpdate = function(){
			renderScroller();
			initDD();
		};
		
		if(scrolling)
			$(window).resize(scrollingUpdate);
		scrolling.data('update', scrollingUpdate);
	});

        // mortgage table scrolling
	$(function(){
		var	titles = $('#mortgage-wrapper .mortgage-title-cell td'),
			values = $('#mortgage-wrapper .mortgage tbody tr');
		if(!titles.length) return;
		titles.each(function(i, title){
			var height = Math.max(title.offsetHeight, values.eq(i).children().eq(0).height());
			//console.log(values.eq(i))
			values.eq(i).children().eq(0).height(height);
			$(title).height(height);
		});
		
		// top scroller
		var topScroller = $('#mortgage-scroller-top'),
			spacer = topScroller.children().width($('#mortgage-wrapper .mortgage tr:eq(0) td').length * 190).height(10),
			scroller = $('#mortgage-wrapper .mortgage-scroller');
		
		topScroller.scroll(function(){
			scroller.scrollLeft(topScroller.scrollLeft());
		});
		scroller.scroll(function(){
			topScroller.scrollLeft(scroller.scrollLeft());
		});
	});
        
	// snap footer to bottom of a short page
	$(function(){
		var
			footer	= $('#footer'),
			win		= $(window),
			paper		= $('.rec-paper'),
			body 		= $('body'),
			snapping = false,
			snap = function(){
				footer.removeClass('footer-snapped').css('top', '');
				var
					fHeight = footer.outerHeight(),
					bHeight = body.height();

				if($.browser.msie && $.browser.version < 8)
					body.hide();

				var winHeight = win.height();
				
				if($.browser.msie && $.browser.version < 8)
					body.show();
				
				if(bHeight < winHeight){
					footer.addClass('footer-snapped').css('top', winHeight - fHeight);
				}
			};
		snap();
		
		var onsnap = function(){
			if(!snapping){

				snapping = true;
				snap();
				setTimeout(function(){
					snapping = false;
					win.one('resize.snapFooter', onsnap);
				}, 100);
			}
		};
		
		win.one('resize.snapFooter', onsnap);
		
		
		// just downloadded images could resize window withouth triggering resize event
		$('img').load(snap);
	});

	// rec and rectop
	(function(){
		$.extend($.fn, {
			//	jQuery plugin 'rec'
			rec: function(c1, c2, c3, c4, color){
				if($.browser.msie && $.browser.version < 7) return this;
				//	create Rec object -> create Raphael path -> attach it to element
				
				$.each(this, function(){
					var $rec = $(this);
					$rec.data('rec', new Rec({
						$rec	: $rec,
						c1		: c1,
						c2		: c2,
						c3		: c3,
						c4		: c4,
						color	: color
					}));
					
					//	collections of all rec elements
					$.recs.push($rec);
				});
				
				return this;
			},
			
			rectop: function(c1, c2, c3, c4, color){
				if($.browser.msie && $.browser.version < 7) return this;
				//	create RecTop object -> create Raphael path -> attach it to element
				
				$.each(this, function(){
					var $rectop = $(this),
						$rectop_children = $rectop.children(),
						$wrapper = $('<div class="rectop-wrapper" />').prependTo($rectop),
						$paper = $('<div class="rectop-paper" />').appendTo($wrapper),
						$container = $('<div class="rectop-container" />').appendTo($wrapper).append($rectop_children),
						paper = Raphael($paper[0], $rectop.width(), $rectop.height());
					
					$rectop.data('rectop', new RecTop({
						$rectop		: $rectop,
						$wrapper		: $wrapper,
						$paper		: $paper,
						$container	: $container,
						paper		: paper,
						c1			: c1,
						c2			: c2,
						c3			: c3,
						c4			: c4,
						color		: color
					}));
					
					//	collections of all rec elements
					$.rectops.push($rectop);
				});
				
				
				
				return this;
			}
		});
		
		//	Rec constructor
		var Rec = function(options){
			this.options = options;
			this.render();
		};
		
		var RecTop = function(options){
			this.options = options;
			this.render();
		};
		
		$.extend(Rec.prototype, {
			render: function(){
				//	find element's constrains
				var	offset = this.options.$rec.offset(),
					width = this.options.$rec.outerWidth(),
					height = this.options.$rec.outerHeight();

				//	ie6-7 bug
				//	jQuery offset for ie < 8 uses getBoundingClientRect() which return wrong values if offset is fractional
				//	it skips dot symbol in returned values
				if($.browser.msie && $.browser.version < 8){
					if((offset.left+'').length > 4)
						offset.left = Math.round(offset.left / 100);
					if((offset.top+'').length > 4)
						offset.top = Math.round(offset.top / 100);
				}	
				
				//	path in SVG path format
				var SVGPath = 
					'M'+ (offset.left + this.options.c1[0]) +' '+ (offset.top + this.options.c1[1]) +					//	left top
					'L'+ (offset.left + width + this.options.c2[0]) +' '+ (offset.top + this.options.c2[1]) +			//	right top
					'L'+ (offset.left + width + this.options.c3[0]) +' '+ (offset.top + height + this.options.c3[1]) +	//	right bottom
					'L'+ (offset.left + this.options.c4[0]) +' '+ (offset.top + height + this.options.c4[1]) +			//	left bottom
					'Z';

				//	create or update path
				if(this.path){
					this.path.attr({ path: SVGPath });
				}else{
					this.path = $.rec.path(SVGPath);
					this.path.attr({ 
						fill: this.options.color,
						'stroke-width': 0,
						'stroke-opacity': 0	//	stroke-width: 0 - doesn't work in Chrome, let's hide stroke with opacity = 0
					});
				}
				
				if(this.options.$rec.css('display') == 'none'){
					this.path.hide();
				}else{
					this.path.show();
				}
			}
		});
		
		$.extend(RecTop.prototype, {
			render: function(){
				//	find element's constrains
				var	offset = this.options.$rectop.offset(),
					width = Math.max.apply( Math, this.options.$container.children().map(function(){
						return $(this).outerWidth();
					}).get()),
					height = this.options.$container.outerHeight();

				//	ie6-7 bug
				//	jQuery offset for ie < 8 uses getBoundingClientRect() which return wrong values if offset is fractional
				//	it skip dot symbol in returned values
				if($.browser.msie && $.browser.version < 8){
					if((offset.left+'').length > 4)
						offset.left = Math.round(offset.left / 100);
					if((offset.top+'').length > 4)
						offset.top = Math.round(offset.top / 100);
				}
				
				var wrapper_offset = this.options.$wrapper.offset();
				offset.left -= wrapper_offset.left;
				offset.top -= wrapper_offset.top;
				
				//	path in SVG path format
				var SVGPath = 
					'M'+ (offset.left + this.options.c1[0]) +' '+ (offset.top + this.options.c1[1]) +					//	left top
					'L'+ (offset.left + width + this.options.c2[0]) +' '+ (offset.top + this.options.c2[1]) +			//	right top
					'L'+ (offset.left + width + this.options.c3[0]) +' '+ (offset.top + height + this.options.c3[1]) +	//	right bottom
					'L'+ (offset.left + this.options.c4[0]) +' '+ (offset.top + height + this.options.c4[1]) +			//	left bottom
					'Z';

				//	create or update path
				if(this.path){
					this.path.attr({ path: SVGPath });
				}else{
					this.path = this.options.paper.path(SVGPath);
					this.path.attr({ 
						fill: this.options.color,
						'stroke-width': 0,
						'stroke-opacity': 0	//	stroke-width: 0 - doesn't work in Chrome, let's hide stroke with opacity = 0
					});
				}
				
				
				if(this.options.$rectop.css('display') == 'none'){
					this.path.hide();
				}else{
					this.path.show();
				}
			}
		});
		
		// onRecReady
		$.recReadyCallbacks = {};
		$.onRecReady = function(name, callback){
			$.recReadyCallbacks[name] = callback;
		}
		
		$(function(){
			if($.browser.msie && $.browser.version < 7) return false;
			//	create canvas and wrap all body elements to put them above the paper
			var
				$genplanPage = $('#genplan-page'),
				$body = $genplanPage.length ? $genplanPage : $('body'),
				$doc = $(document),
				$win = $(window),
				$page = $('<div class="rec-page" />').append($body.children()).appendTo($body),
				$paper = $('<div class="rec-paper" />').width($win.width()).height($doc.height()).prependTo($body);
			
			//	lets find document width through $(window).width(), not $(document).width()
			//	because ie8 bug (adding sroll pane width)
			//	we have to be ensured that we have no horizontal scrolling on fullscreen to use that hack
				
			//	canvas
			$.rec = Raphael($paper[0], $paper.width(), $paper.height());
			$paper.data('rec', $.rec);
			//	rec elements collection
			$.recs = [];
			$.rectops = [];
			
			
			var updating = false;
			
			//	resize canvas and rerender all recs on window resize
			$win.bind('resize.rec', function(){
				if(!updating)
					setTimeout(function(){
						$paper.hide();
						var	width = $win.width(),
							height = $doc.height();
						$paper.width(width).height(height).show();
						$.rec.setSize(width, height);
						$.each($.recs, function(){
							this.data('rec').render();
						});
					}, 200);
			});
			
			var updateRectops = function(){
				if($.browser.msie && $.browser.version <= 8){
					updating = true;
				}
				$.each($.rectops, function(){
					var rectop = this.data('rectop');
					rectop.options.$paper.hide();
				});
				$.each($.rectops, function(){
					var	rectop = this.data('rectop'),
						width = Math.max.apply( Math, rectop.options.$container.children().map(function(){
							return $(this).outerWidth();
						}).get()),
						height = rectop.options.$container.outerHeight();
					rectop.options.$paper.width(width).height(height).show();
					rectop.options.paper.setSize(width, height);
					rectop.render();
				});
				if($.browser.msie && $.browser.version <= 8)
					setTimeout(function(){
						updating = false;
					}, 200);
			};
			
			setTimeout(updateRectops, 200);
			$win.bind('resize.rectop', function(){
				if(!updating)
					setTimeout(updateRectops, 200);
			});
			
			$.each($.recReadyCallbacks, function(){
				this.call();
			});
			
			
		});
	})();
	// facade interactions
	$(function(){
		var
			wrapper = $('.facade-wrapper'),
			scrollerScheme = $('.ffacade-scroller-scheme'),
			facade = wrapper.children('table.facade'),
			wrapperOffset = wrapper.offset();
		
		//	create facade row hover
		var hover = $('<div class="facade-row-hover"><div></div></div>').css('opacity', .3).insertAfter(facade).children().css('opacity', .5).end();
		var selected = $('<div class="facade-row-hover"><div></div></div>').css('opacity', .75).insertAfter(facade).children().css('opacity', .5).end();
		
		//	handle floor selection
		var 
			flatMap = {
				1: 'однокомнатная',
				2: 'двухкомнатная',
				3: 'трехкомнатная',
				4: 'четырехкомнатная',
				5: 'пятикомнатная',
				6: 'шестикомнатная',
				7: 'семикомнатная',
				8: 'восьмикомнатная'
			},
			description = $('.floor-description-wrapper'),
			apartmentDetails = $('.apartment-details'),
			descriptionGreen = description.children().eq(0).children('ul'),
			descriptionRed = description.children().eq(1).children('ul'),
			descriptionGray = description.children().eq(2).children('ul'),
			floorMap = $('#floor-map'),
			floorMapUpper = floorMap.prev().children('span.section'),
			floorMapCaption = floorMap.children('.floor-map-caption'),
			floorMapImage = floorMapCaption.children('img'),
			floorMapFloor = floorMapCaption.children('span.floor'),
			floorMapSection = floorMapCaption.children('span.section'),
			moreInfo = $('#facade-more-info'),
			moreFloor = moreInfo.children('span.floor'),
			moreTotal = moreInfo.children('span.total');
			
		hover.click(function(){
			var
				row = hover.data('row'),
				prev_facade_section = facade.children().children().children().children('.facade-section[rel='+ miniplan_data.section_active +']'),
				offset = row.offset(),
				wrapperOffset = wrapper.offset(),
				section_table = row.closest('table'),
				width = row.width();
			
			// miniplan interaction
			section_table.data('miniplan').active.attr({
				opacity: 1
			});
			
			if(section_table[0] != prev_facade_section[0]){
				prev_facade_section.data('miniplan').active.attr({
					opacity: 0
				});
			}
			miniplan_data.section_active = section_table.attr('rel');
			
			//------------------------
			
			apartmentDetails.empty();
			
			selected.width(width).css({
				left: (offset.left - wrapperOffset.left) + 'px',
				top: (offset.top - wrapperOffset.top) + 'px'
			}).show();
			
			
			var
				section = row.closest('td'),
				floor = row.parent().children().length - row.parent().children().index(row[0]) - 1,
				index = section.parent().children().index(section[0]);
				
			// show selected section on facade scroller
			scrollerScheme.find('td').eq(index + 1).addClass('active').siblings('.active').removeClass('active');
			
			// change sections number above floor's map
			floorMapSection.text(index + 1);
			floorMapUpper.text(index + 1);
			floorMapFloor.text(floor);
			moreFloor.text(floor);
			moreTotal.text(row.data('floor').total);
			moreInfo.add(description).show();
			descriptionGreen.add(descriptionRed).add(descriptionGray).empty();
			var floorData = row.data('floor');
			if(floorData.apartments.green){
				$.each(floorData.apartments.green, function(){
					var data =this.split(':');
					$('<li><a class="apartment-preview" href="'+data[1]+'">'+ flatMap[data[0]] +'</a></li>').appendTo(descriptionGreen);
				});
			}
			if(floorData.apartments.red){
				$.each(floorData.apartments.red, function(){
					var data =this.split(':');
					$('<li><a class="apartment-preview" href="'+data[1]+'">'+ flatMap[data[0]] +'</a></li>').appendTo(descriptionRed);
				});
			}
			if(floorData.apartments.gray){
				$.each(floorData.apartments.gray, function(){
					var data =this.split(':');
					$('<li><a class="apartment-preview" href="'+data[1]+'">'+ flatMap[data[0]] +'</a></li>').appendTo(descriptionGray);
				});
			}

            $('div#floor-map > img').attr("src", "http://objects.asmsoft.ru/backend_dev.php/ajax/getFloorPlan?section_id="+floorData.apartments.section_id+"&floor="+floorData.apartments.floor);

		});
		
		// init apartment description link click
		description.delegate('a.apartment-preview', 'click', function(){
			description.find('li.active').removeClass('active');
			apartmentDetails.empty().addClass('apartment-details-loading');
			var
				$this = $(this),
				id = $this.attr('href');
			$this.parent().addClass('active');
			$.ajax({
				url: apartmentDetailsUrl,
				data: {id: id},
				dataType: 'json',
				success: function(response){
					apartmentDetails.removeClass('apartment-details-loading');
					if(response.url) $('<a class="button-apartment-details" href="'+ response.url +'">').appendTo(apartmentDetails);
					if(response.url && response.num) $('<h3><a href="'+ response.url +'">Квартира №'+ response.num +'</a></h3>').appendTo(apartmentDetails);
					if(response.price) $('<div class="price">'+ response.price +' Руб.</div>').appendTo(apartmentDetails);
					if(response.image) $('<div class="apartment-map"><img src="'+ response.image +'" alt="" /></div>').appendTo(apartmentDetails);
				},
				error: function(error){
					apartmentDetails.removeClass('apartment-details-loading');
					alert('Ошибка загрузки данных о квартире');
				}
			});
			
			return false;
		});
		
		
		//	init facade row hover
		var rows = $('table.facade-section tbody tr');
		rows.filter(':not(.first-floor)').mouseenter(function(){
			var 
				$this = $(this),
				offset = $this.offset(),
				wrapperOffset = wrapper.offset(),
				width = $this.width();
				
			hover.data('row', $this).width(width).css({
				left: (offset.left - wrapperOffset.left) + 'px',
				top: (offset.top - wrapperOffset.top) + 'px'
			}).show();
		});
		
		// handle apartment data
		rows.filter(':not(.first-floor)').each(function(){
			var
				$this = $(this),
				total = 0,
				apartments = {
					green	: $this.attr('green'),
					red	: $this.attr('red'),
					gray	: $this.attr('gray'),
                    section_id : $this.attr('section_id'),
                    floor:  $this.attr('floor')
				};
			$.each(apartments, function(color){
				if(apartments[color]){
					apartments[color] = apartments[color].split(',');
					total += apartments[color].length;
				}
			});
			
			$this.data('floor', {
				total: total,
				apartments: apartments
			});
			
			// show green flats
			setTimeout(function(){
				var
					offset			= $this.offset(),
					flatsTotal		= $this.children().length,
					flatPositions	= {},
					generatePosition = function(){
						var pos = Math.floor(Math.random() * flatsTotal);
						if(flatPositions[pos]) return generatePosition();
						else {
							flatPositions[pos] = true;
							return pos;
						}
					};
				
				if(apartments.green){
					$.each(apartments.green, function(){
						var
							pos = generatePosition(),
							apartmentData = this.split(':'),
							rooms = apartmentData[0],
							id = apartmentData[1];
						$('<div class="facade-flat-button"><div class="top">'+ rooms +' к</div><div class="bottom">'+ rooms +' к</div></div>').data('row', $this).css({
							opacity: .8,
							top: (offset.top - wrapperOffset.top) + 'px',
							left: (offset.left - wrapperOffset.left + 35 * pos) + 'px'
						}).appendTo(wrapper).mouseenter(function(){
							$(this).data('row').mouseenter();
						}).click(function(){
							hover.click();
						});
					});
				}
			}, 0);
			
		});
		
		//	init facade shadows
		var balconies = rows.children('.balcony-white').add(rows.children('.balcony-blue')),
		_init = function(cell){
			if(!cell.children().length)
				cell.append('<div />');
		},
		handle_left = function(cell){
			_init(cell);
			cell.children().append('<div class="facade-shadow-right"/>');
		},
		handle_right = function(cell){
			_init(cell);
			cell.children().append('<div class="facade-shadow-left"/>');
		},
		handle_bottom = function(cell){
			_init(cell);
			cell.children().append('<div class="facade-shadow-top"/>');
		};
		
		balconies.each(function(){
			var	balcony = $(this),
				parent = balcony.parent(),
				left = balcony.prev(),
				right = balcony.next(),
				bottom = parent.next().children().eq(parent.children().index(this));
			
			handle_left(left);
			handle_right(right);
			handle_bottom(bottom);
		});
	});

	// facade scrolling
	$(function(){
		
		var
			facadeContainer	= $('.facade-container'),
			facadeWrapper		= $('.facade-wrapper'),
			facade				= facadeWrapper.children('table.facade'),
			scrollerContainer	= $('.facade-scroller-container'),
			scrollerWrapper	= scrollerContainer.children('.ffacade-scroller-wrapper'),
			scrollerScheme		= scrollerWrapper.children('.ffacade-scroller-scheme'),
			scrollerLeft		= scrollerWrapper.children('.ffacade-scroller-left'),
			scrollerBg			= scrollerWrapper.children('.ffacade-scroller-bg'),
			scrollerRight		= scrollerWrapper.children('.ffacade-scroller-right'),
			arrowLeft			= scrollerScheme.find('.ffacade-scroller-arrow-left'),
			arrowRight			= scrollerScheme.find('.ffacade-scroller-arrow-right'),

			// relative delta between centers of facade and container
			delta					= 0,
			
			// update scroller view
			updateScroller = function(){
				if(!facadeWrapper.is(':visible')) return;
				var
					scrollerContainerWidth = scrollerContainer.width(),
					wrapperOffset		= facadeWrapper.offset(),
					containerOffset	= facadeContainer.offset(),
					wrapperWidth		= facadeWrapper.width(),
					containerWidth		= facadeContainer.width(),
					scrollWidth			= (scrollerContainerWidth - 20) * .8;
				
				//	update scroller frame
				var
					left		= (containerOffset.left - wrapperOffset.left) * (scrollWidth / wrapperWidth) + 14,
					bgLeft	= left + 23,
					bgWidth	= (scrollWidth / wrapperWidth) * containerWidth - 74,
					right		= bgLeft + bgWidth - 1;
				
				scrollerLeft.css('left', left);
				scrollerBg.css('left', bgLeft).width(bgWidth);
				scrollerRight.css('left', right);
			},
			
			// update facade position on window resize and on facade scroll
			updateFacadePosition = function(){
				var
					wrapperWidth	= facadeWrapper.width(),
					containerWidth	= facadeContainer.width();
				
				if(containerWidth > wrapperWidth) {
					delta = 0;
				}
				
				setTimeout(function(){
					var
						wrapperOffset	= facadeWrapper.offset(),
						containerOffset = facadeContainer.offset(),
						wrapperWidth	= facadeWrapper.width(),
						containerWidth	= facadeContainer.width();
					if((containerWidth > wrapperWidth) && (wrapperOffset.left - containerOffset.left > 20) && (wrapperOffset.left + wrapperWidth < containerOffset.left + containerWidth - 20)){
						scrollerWrapper.hide();
					}else{
						scrollerWrapper.show();
					}
					
					if(scrollerWrapper.is(':visible')){
						// check whether facade borders are far from container borders and snap facade to container in this case
						if(containerWidth/2 - wrapperWidth/2 + delta*wrapperWidth > 0){
							facadeWrapper.css({'left': 30});
							updateScroller();
						}
						if(containerWidth/2 - wrapperWidth/2 + delta*wrapperWidth + wrapperWidth < containerWidth){
							facadeWrapper.css({left: containerWidth - wrapperWidth - 30});
							updateScroller();
						}
					}
				}, 2);
				facadeWrapper.css({left: containerWidth/2 - wrapperWidth/2 + delta*wrapperWidth});
				updateScroller();
			};
		setTimeout(updateFacadePosition, 20);
		
		// scroller buttons
		arrowLeft.click(function(){
			var
				wrapperOffset		= facadeWrapper.offset(),
				containerOffset	= facadeContainer.offset(),
				wrapperWidth		= facadeWrapper.width(),
				containerWidth		= facadeContainer.width();
			
			if((containerOffset.left + 30 > wrapperOffset.left)){
				delta += Math.min(50, containerOffset.left + 30 - wrapperOffset.left) / wrapperWidth;
				updateFacadePosition();
			}
		});

		arrowRight.click(function(){
			var
				wrapperOffset		= facadeWrapper.offset(),
				containerOffset	= facadeContainer.offset(),
				wrapperWidth		= facadeWrapper.width(),
				containerWidth		= facadeContainer.width();
			
			
			if(wrapperOffset.left + wrapperWidth > containerOffset.left + containerWidth - 30){
				delta -= Math.min(50, wrapperOffset.left + wrapperWidth - containerOffset.left - containerWidth + 30) / wrapperWidth;
				updateFacadePosition();
			}
		});
		
		if(facade)
			$(window).resize(function(){
				setTimeout(updateFacadePosition, 0);
			});
	});
	
	// search results
	(function(){
		setTimeout(function(){
			var
				searchResultsTable = $('.search-results-table'),
				rows = searchResultsTable.children('tbody').children('tr');
		
			rows.mouseenter(function(){
				$(this).addClass('selected').siblings('.selected').removeClass('selected');
			});
			
			var
				searchResultsList = $('.search-results-list'),
				lis = searchResultsList.children();
			
			lis.mouseover(function(){
				var li = $(this);
				li.css({width: '160px', height: li.children().outerHeight()}).addClass('active').siblings('.active').mouseleave();
				
				if($.browser.msie && $.browser.version < 9){
					li.children().addClass('search-card-active');
				}
			}).mouseout(function(){
				var li = $(this);
				li.removeClass('active').css({width: 'auto', height: 'auto'});
				if($.browser.msie && $.browser.version < 9){
					li.children().removeClass('search-card-active');
				}
			});
			
		}, 0);
	})();
	
	// home page map
	(function(){
		$.fn.homemap = function(url){
			var	container = this,
				oImg = new Image(),
				ratio = null,
				legendWidth = $('.home-map-legend').outerWidth(),
				area = $('#home-map-area'),
				img = $('<img />'),
				resize = function(){
					img.hide();
					var width = area.width() - legendWidth - 50; 
					img.width(width).height(width / ratio).show();
				};
				
			oImg.onload = function(){
				ratio = oImg.width / oImg.height;
				img.attr('src', url).appendTo(container);
				resize();
				//	redraw bg recs
				$(window).trigger('resize.rec');
				
			};
			oImg.src = url;
			
			$(window).bind('resize.homemap', resize);
			
		};
		$(function(){
			$('#home-map-img').children('.home-map-img-wrapper').homemap('/i/home-map.jpg');
		});
	})();
	
	// home page area switcher
	$(function(){
		var
			areaMap		= $('#home-map-area'),
			areaNumbers	= $('#home-numbers-area'),
			areaPhotos	= $('#home-photos-area'),
			menu			= $('#menu-left'),
			welcome		= $('#welcome'),
			galInit		= false,
			links			= menu.find('a');
		
		// home page gallery
		var gallery = (function(){
			var
				gal = $('#home-photos-area'),
				gallery = $('<div class="home-gal" />').appendTo(gal),
				desc = $('<div class="home-gal-desc" />').appendTo(gallery),
				arrow_left = $('<div class="home-gal-arrow-left" />').appendTo(gallery),
				arrow_right = $('<div class="home-gal-arrow-right" />').appendTo(gallery),
				divs = gal.children('.img'),
				imgs = {},
				win = $(window),
				
				// update image description
				updateDesc = function(path){
					if(!desc || !desc.length) return;
					desc
						.text(divs.filter('[rel="'+path+'"]').text())
						.width(gallery.children('img:visible').width()/4)
						.show();
				},
				
				// resize image
				resize = function(img){
					if(!img) return;
					img.hide().width(gal.width());
					img.show();
					arrow_left.css({
						top: img.height() / 2 - 12
					});
					arrow_right.css({
						top: img.height() / 2 - 12
					});
					updateDesc(img.attr('rel'));
				},
				
				// load and show image
				init = function(path){
					arrow_left.add(arrow_right).add(desc).hide();
					if($.browser.msie && $.browser.version < 7){
						var img = new Image();
						img.src = path;
						var $img = $('<img />').appendTo(gallery).hide();
						gallery.addClass('home-gal-loading');
						img.onload = function(){
							gallery.removeClass('home-gal-loading');
							$img.attr('src', path).attr('rel', path).show();
							arrow_left.add(arrow_right).show();
							resize($img);
							win.resize();
						}
						imgs[path] = $img;
					}else{
						gallery.addClass('home-gal-loading');
						var img = $('<img rel="'+path+'" src="'+ path +'" />').hide().load(function(){
							gallery.removeClass('home-gal-loading');
							$(this).show().data('defWidth', this.width);
							arrow_left.add(arrow_right).show();
							resize($(this));
							win.resize();
						}).appendTo(gallery);
					}
				};
			
			arrow_right.click(function(){
				var
					path = gallery.children('img:visible').attr('rel'),
					next = gal.children('[rel="'+ path +'"]').next('.img');
				if(!next.length) next = gal.children('.img').eq(0);
				gallery.children('img:visible').hide();
				if(imgs[next.attr('rel')]){
					resize(imgs[next.attr('rel')].show());
				}else{
					init(next.attr('rel'));
				}
			});
			
			arrow_left.click(function(){
				var
					path = gallery.children('img:visible').attr('rel'),
					prev = gal.children('[rel="'+ path +'"]').prev('.img');
				if(!prev.length) prev = gal.children('.img').eq(gal.children('.img').length - 1);
				gallery.children('img:visible').hide();
				if(imgs[prev.attr('rel')]){
					resize(imgs[prev.attr('rel')].show());
				}else{
					init(prev.attr('rel'));
				}
			});
			
			
			// window resize
			var resizing = false;
			
			var onresize = function(){
				if(!resizing){
					resizing = true;
					resize(gallery.children('img:visible'));
					setTimeout(function(){
						resizing = false;
						win.one('resize.resizeHomeGallery', onresize);
					}, 100);
				}
			}
			
			win.one('resize.resizeHomeGallery', onresize);
				
			return {
				init: function(){
					init(divs.eq(0).attr('rel'));
				}
			}
		})();

		links.click(function(){
			var
				a = $(this),
				li = a.parent(),
				type = this.className;
			if(li.is('.active')) return false;
			
			// hide active area
			$('#' + li.siblings('.active').children()[0].className).hide();
			var
				index = li.parent().children().index(li[0]) + 1;
				activeIndex = li.parent().children().index(li.siblings('.active')) + 1,

			li.siblings('.active').removeClass('active').removeClass('active-' + activeIndex);
			li.addClass('active').addClass('active-' + index);
			$('#' + type).show();
			
			if(index == 3){
				welcome.hide();
				if(!galInit) {
					galInit = true;
					gallery.init();
				}
			}else{
				welcome.show();
			}
			
			// touch window resize to hide path of hidden areas
			$(window).resize();
			
			return false;
		});
	});
	
	// main menu handler
	$(function(){
		var
			menu = $('#menu'),
			links = menu.find('a'),
			submenu = $('.sub-menu-container').find('td');
		
		links.click(function(){
			var
				$a = $(this),
				li = this.parentNode,
				$li = $(li),
				index = $li.parent().children().index(li) + 1;
			
			if($li.is('.active')) return false;
			
			$li.siblings('.active')[0].className = "";
			$li.addClass('active').addClass('active-' + index);
			submenu[0].className = 'active-' + index;
			
			$(window).resize();
			return false;
		});
	});
	
	// select apartments --> select for order checkboxes
	$(function(){
		var
			apartments = $('.apartments-selected'),
			chbxs = apartments.find('input[type=checkbox]'),
			updateChbx = function(){
				var
					chbx = $(this),
					td = chbx.closest('td'),
					tds = td.parent().children(),
					index = tds.index(td[0]),
					targetTd = apartments.find('tr').eq(0).children().eq(index);
				if(chbx.is(':checked')) {
					targetTd.addClass('selected');
				}else{
					targetTd.removeClass('selected');
				}
				
				return targetTd.attr('rel');
			};
		chbxs
			.filter(':checked')
				.each(updateChbx)
				.end()
			.click(function(){
				var that = this;
				
				// update checkbox an apartment view
				setTimeout(function(){ 
					var id = updateChbx.call(that);
					$.ajax({
						url: 'select-apartment.json',
						data: {id: id, action: $(that).is(':checked') ? 'add' : 'delete'},
						dataType: 'json',
						success: function(response){},
						error: function(error){
							alert('Ошибка передачи данных');
						}
					});
				}, 20);
			});
	});
	
	$.overlay = function(options){
		var overlay = $('<div class="overlay" />').appendTo('body');
		if($.browser.msie && $.browser.version < 7){
			overlay.append("<iframe scrolling='no' frameborder='0' style='position: absolute; top: 0; left: 0; width: 100%; height: 100%; filter:alpha(opacity=0)'></iframe>");
		}
		
		return overlay;
	};
	
	
	$.extend($.fn, {
		popup: function(options){
			return this.each(function(){
				if($(this).data('popup')){
					var popup = $(this).data('popup');
					$.extend(true, popup.settings, options);
				}else $(this).data('popup', new Popup(this, options));
			});
		}
	});
	
	Popup = function(elem, options){
		this.elem = $(elem);
		var cssWidth = elem.style.width;
		this.settings = $.extend(true, {
			width: cssWidth ? parseInt(cssWidth) + 20 + 'px' : '520px'
		}, options);
		
		this.div = $('<div class="popup" />').appendTo('body').css({
			width: this.settings.width
		});
		
		var titleText = this.elem.attr('title');
		this.elem.removeAttr('title');
		this.title = $('<h1>'+ titleText +'</h1>').appendTo(this.div);
		
		this.content = $('<div class="popup-content" />').append(this.elem).appendTo(this.div);
		
		this.elem.show();
		
		this.closeButton = $('<a href="#" class="popup-close-button"></a>')
			.appendTo(this.div)
			.click((function(popup){
				return function(){
					popup.close()
					return false;
				}
			})(this));
			
		(function(elem){
			setTimeout(function(){
				elem.trigger('popup-init');
			}, 0);
		})(this.elem)
	};
	
	$.extend(Popup.prototype, {
		open: function(){
			this.overlay = $.overlay();
			this.div.show();
			this.center();
			var popup = this;
			this.elem.trigger('popup-open');
			var center = function(){
				popup.center();
			};
			$(window).bind('resize.popup', center);
			$(document).bind('scroll.popup', center);
			return this;
		},
		
		close: function(){
			this.div.hide();
			this.overlay.remove();
			
			this.elem.trigger('popup-close');
			
			$(window).unbind('resize.popup');
			$(document).unbind('scroll.popup');
			return this;
		},
		
		center: function(){
			var
				el = this.div,
				header = this.title,
				hHeight = header.outerHeight(),
				win = $(window),
				doc = $(document);
			
			this.content.addClass('popup-content-full-height');
			el.css('height', 'auto');
			this.content.css('height', 'auto');
			var h = el.outerHeight();
			this.content.removeClass('popup-content-full-height');
			
			if(win.height() - 200 - hHeight < h){
				el.css('height', win.height() - 200 );
				this.content.height(win.height() - 200 - hHeight);
			}else{
				el.css('height', 'auto');
				this.content.css('height', 'auto');
			}
			el.css('top', 100 + doc.scrollTop());
			el.css('left', Math.max(10, Math.round(win.width()/2 + doc.scrollLeft() - el.width()/2)));
			return this;
		}
	});
	
	$(function(){
		$('.popup-food').popup();
		$('[rel^=popup]').each(function(){
			var
				$this = $(this),
				popupId = $this.attr('rel').substr(6),
				popup = $('#' + popupId);
				
			$this.click(function(){
				var popupObj = popup.data('popup');
				if(popupObj)
					popupObj.open();
				return false;
			})
			
		})
	});
	
	// order selected apartments popup
	$(function(){
		// handle buy apartments popup
		var popup_el = $('#popup-buy-apartment');
		if(!popup_el.length) return;
			
		var
			popup = popup_el.data('popup'),
			popup_header = popup.title,
			apartments_list = popup_el.find('.apartments-list');
		
		popup_el.bind('popup-open', function(){
			$.ajax({
				cache: false,
				url: selectedApartmentUrl,
				dataType: 'json',
				success: function(response){
					if(response.length < 2) popup_header.text('ЗАЯВКА НА ПОКУПКУ КВАРТИРЫ');
					else popup_header.text('ЗАЯВКА НА ПОКУПКУ КВАРТИР ('+ response.length +')');
					var apartments_html = '';
					for(var i = 0; i < response.length; i++){
						apartments_html +=
							'<div class="apartment-description">' +
								'<div>Дом: <b>'+ response[i].addr +'</b></div>' +
								'<div>Квартира: <b>'+ response[i].apartment +'</b></div>' +
								'<div>Общая площадь: <b>'+ response[i].square +'</b></div>' +
							'</div>';
					}
					apartments_list.removeClass('loading').append(apartments_html);
					popup.center();
				},
				error: function(error){
					alert('Ошибка загрузки данных о выбранных квартирах');
				}
			});
		});
		
		popup_el.bind('popup-close', function(){
			apartments_list.empty().addClass('loading');
		});
	});
	
	// reviewed apartments-popup
	$(function(){
		var
			popup_el = $('#popup-reviewed'),
			popup = popup_el.data('popup');
		
		//	put 'clear list' anchor into the title
		popup_el.bind('popup-init', function(){
			popup.title.append(popup_el.children('a.popup-reviewed-clear-list'));
		}).bind('popup-open', function(){
			popup_el.empty().addClass('loading');
			popup.center();
			$.ajax({
				cache: false,
				url: '_reviewed-apartments.html',
				dataType: 'html',
				success: function(response){
					popup_el.removeClass('loading').append(response);
					popup.center();
				},
				error: function(error){
					alert('Ошибка загрузки данных о просмотренных квартирах');
				}
			});
		});
	});
	
	// genplan
	$(function(){
		var
			genplan = $('#genplan'),
			map = $('#genplan-map'),
			how2 = $('.genplan-how-to-use span'),
			how2popup = $('.genplan-how-to-use-popup'),
			border = map.children();
			
		if(!genplan.length) return;
		
		var
			win = $(window),
			bg = $('#genplan-bg'),
			paper = Raphael(bg[0], 2100, 1600),
			body = $('#genplan-page'),
			resizingGenplan = false,
			updateMap = function(){
				var
					w = win.width(),
					h = win.height(),
					l = -parseInt(bg.css('left')),
					t = -parseInt(bg.css('top'));
				border.css({
					left: l/10,
					top: t/10,
					width: w/10 - 2,
					height: h/10 - 2
				});
			},
			resizeGenplan = function(){
				body.hide();
				var
					w = win.width(),
					h = win.height();
				genplan.width(w).height(h);
				body.show();
				updateMap();
			},
			center = function(){
				bg.css({
					/*left: win.width()/2 - 1050,
					top: win.height()/2 - 800*/
					left: -150,
					top: -150
				});
			},
			rec_paper = $('#genplan-page').children('.rec-paper'),
			bgw = bg.width(),
			bgh = bg.height(),
			houses = []; // array of pathes of houses on rec_paper		
		
		genplan.show();
		resizeGenplan();
		center();
		updateMap();
		
		how2.mouseover(function(){
			how2popup.show();
		}).mouseout(function(){
			how2popup.hide();
		});
		var resizingGenplan = false;
		
		var onresize = function(){
			if(!resizingGenplan){
				resizingGenplan = true;
				resizeGenplan();
				setTimeout(function(){
					resizingGenplan = false;
					win.one('resize.resizeGenplan', onresize);
				}, 100);
			}
		}
		
		win.one('resize.resizeGenplan', onresize);
		
		var arrayToSVGPath = function(a, dx, dy){
			if(!dx) dx = 0;
			if(!dy) dy = 0;
			//	path in SVG path format
			var svgPath = 'M'+ (a[0][0] + dx) +' '+ (a[0][1] + dy);
			for(var i = 1; i < a.length; i++ ){
				svgPath += ('L'+ (a[i][0] + dx) +' '+ (a[i][1] + dy));
			}
			svgPath += 'Z';
			
			return svgPath;
		};
		
		// init plane
		var plane = $('<div class="gp-plane"><div class="description"><div class="num"></div><div class="street"></div><div class="status"></div><div class="proposal">Квартиры в продаже</div><div class="room-1"><span>однокомнатных:</span> <b></b></div><div class="room-2"><span>двухкомнатных:</span> <b></b></div><div class="room-3"><span>трехкомнатных:</span> <b></b></div></div></div>').appendTo(bg);
		
		
		var recPaperHouses = function(paper){
			if($.browser.msie && $.browser.version < 7){
				var
					dx = 0,
					dy = 0;
			}else{
				var
					dx = parseInt(bg.css('left')),
					dy = parseInt(bg.css('top')),
					paper = rec_paper.data('rec');
			}
			
			if(houses.length){
				// update
				$.each(houses, function(i){
					this.attr('path', arrayToSVGPath(genplan_data[i].coords, dx, dy));
				});
			}else{
				// init
				$.each(genplan_data, function(){
					var path = paper.path(arrayToSVGPath(this.coords, dx, dy));
					(function(data){
						path
							.attr({
								opacity: 0,
								'stroke-width': 2,
								stroke: '#ffb400',
								fill: '#FFF',
								cursor: 'pointer'
							})
							.mouseover(function(){
								this.attr({
									opacity: .5
								});
								// fill in plane data
								var desc = plane.children();
								
								if(!data.street) data.street = '';
								if(!data.status) data.status = '';
								
								desc.children('.num').text(data.num);
								desc.children('.street').text(data.street);
								desc.children('.status').text(data.status);
								if(data.flats){
									desc.children('.proposal').show();
									desc.children('.room-1').add(desc.children('.room-2')).add(desc.children('.room-3')).show();
									desc.children('.room-1').children('b').text(data.flats[1]);
									desc.children('.room-2').children('b').text(data.flats[2]);
									desc.children('.room-3').children('b').text(data.flats[3]);
								}else{
									desc.children('.proposal').hide();
									desc.children('.room-1').add(desc.children('.room-2')).add(desc.children('.room-3')).hide();
								}
								plane.css({
									left: data.plane[0] - 202,
									top: data.plane[1] - 61
								}).show();
							})
							.mouseout(function(){
								this.attr({
									opacity: 0
								});
								plane.hide();
							});
						if(data.url){
							path.click(function(){
								document.location.href = data.url;
							})
						}
						houses.push(path);
					})(this);
				});
			}
		};
		recPaperHouses(paper);
		
		if($.browser.msie && $.browser.version < 7){
			var rec_paper = genplan;
		}
		
		// drag'n'drop
		rec_paper.dd({
			proxy: $('<div id="geplann-dd-proxy" />').appendTo(rec_paper),
			position: 'absolute'
		}).bind('dd-start', function(){
			rw = rec_paper.width();
			rh = rec_paper.height();
			var dd = rec_paper.data('dd');
			dd.proxy.css({ left: '0', top: '0' });
			
			dd._start_bg_pos = {
				left: parseInt(bg.css('left')) || 0,
				top:parseInt(bg.css('top')) || 0
			};
		}).bind('dd-drag-after', function(){
			var
				dd = rec_paper.data('dd'),
				newLeft = Math.min(0, Math.max(dd._start_bg_pos.left + parseInt(dd.proxy.css('left')), rw - bgw)),
				newTop = Math.min(0, Math.max(dd._start_bg_pos.top + parseInt(dd.proxy.css('top')), rh - bgh));
			
			// update bg position
			bg.css({	left: newLeft, top: newTop	});
			
			updateMap();
			recPaperHouses();
		});
	});

	
	// faq
	$(function(){
		$('#faq').children().children('a').click(function(){
			var
				$this = $(this),
				parent = $this.parent(),
				div = $this.next();
			
			$this.parent().toggleClass('active');
			if(parent.is('.active')){
				div.slideDown(function(){$(window).resize()});
			}else{
				div.slideUp(function(){$(window).resize()});
			}
			
			return false;
		});
	});
	
	// pretty photo
	$(function(){
		if($.fn.prettyPhoto){
			$('a[rel^="prettyPhoto"]').prettyPhoto();
		}
	});
        
	// miniplan
	$(function(){
		var plan = $('#plan-micro');
		if(!plan.length) return;
		var
			facade = $('table.facade'),
			sections = facade.find('table.facade-section'),
			row_hover = $('div.facade-row-hover[rel=target]'),
			paper = Raphael('plan-micro', 240, 190),
			arrayToSVGPath = function(a, dx, dy){
				if(!dx) dx = 0;
				if(!dy) dy = 0;
				//	path in SVG path format
				var svgPath = 'M'+ (a[0][0] + dx) +' '+ (a[0][1] + dy);
				for(var i = 1; i < a.length; i++ ){
					svgPath += ('L'+ (a[i][0] + dx) +' '+ (a[i][1] + dy));
				}
				svgPath += 'Z';
				
				return svgPath;
			};
		
		for(var section in miniplan_data.sections){
			var
				path = arrayToSVGPath(miniplan_data.sections[section].coords),
				facade_section = sections.filter('[rel=' + section + ']'),
				rows = facade_section.children('tbody').children('tr'),
				border = paper.path(path)
					.attr({
						opacity: 0,
						'stroke-width': 2,
						stroke: '#1ebff3'
					}),
				active = paper.path(path)
					.attr({
						opacity: 0,
						'stroke-width': 2,
						stroke: '#FF0000'
					});
				
			(function(border, data, section, border, active, rows){
				var hover = paper.path(path)
					.attr({
						opacity: 0,
						fill: '#000',
						cursor: 'pointer'
					})
					.mouseover(function(){
						if(miniplan_data.section_active != section)
						border.attr({
							opacity: 1
						});
					}).mouseout(function(){
						border.attr({
							opacity: 0
						});
					}).click(function(){
						if(miniplan_data.sections[miniplan_data.section_active].building != data.building){
							// click on another building -> go to another facade page
							location.href = data.url;
						}else{
							// change active section
							if(miniplan_data.section_active == section) return;
							row_hover.data('row', rows.eq(Math.ceil(rows.length/2))).click();
						}
					});
				
				sections.filter('[rel='+ section +']').data('miniplan', {
					hover: hover,
					active: active,
					border: border
				});
			})(border, miniplan_data.sections[section], section, border, active, rows);
			
			if(miniplan_data.section_active == section){
				row_hover.data('row', rows.eq(Math.ceil(rows.length/2))).click();
			}
		}
	});
	
	// scroll links
	$(function(){
		var body = $.browser.webkit ? $(document.body) : $(document.documentElement);
		$('a.scroll-link').click(function(){
			var
				$this = $(this),
				href = $this.attr('href');
			
			var target = $(href);
			if(!target.length) return false;
			var pos = target.offset().top;
			body.animate({ scrollTop: pos}, pos);
			
			
			return false;
		});
	});
	
	// content galleries
	$(function(){
	// galleries switcher
		var
			menu = $('.content-gal-menu'),
			descriptions = $('.building-description').children(),
			active = menu.children('.active').children(),
			switchers = menu.children().children(),
			galls = $('div.content-gal-wrapper');
		
		switchers.click(function(){
			var
				switcher = $(this),
				href = switcher.attr('href');
			
			switcher.parent().addClass('active').siblings('.active').removeClass('active');
			
			var gal = galls.filter(href).show();
			gal.siblings('div.content-gal-wrapper:visible').hide();
			gal.children('ul.content-gal-thumbs').children('.active').children().click();
			
			descriptions.filter(href + '-desc').show().siblings(':visible').hide();
			return false;
		});
		
		active.click();
	
	// galleries
		var showImage = function(thumb){
			var
				area = thumb.data('photo-area').empty().addClass('loading'),
				href = thumb.attr('href');
			if(thumb.data('img')){
				area.removeClass('loading').append('<img src="'+ href +'" />');
			}else{
				var img = new Image();
				thumb.data('img', img);
				img.onload = function(){
					area.removeClass('loading').append('<img src="'+ href +'" />');
				};
				
				img.src = href;
			}
			
			thumb
				.parent()
					.addClass('active')
					.siblings('.active')
						.removeClass('active');
		};
		galls.each(function(){
			var
				gal = $(this),
				photo = gal.children('.content-gal-photo'),
				thumbs = gal.children('.content-gal-thumbs')
					.children()
						.children('a.thumb')
							.data('photo-area', photo);

			thumbs.click(function(){
				var thumb = $(this);
				showImage(thumb);
				return false;
			});
			
			gal.filter(':visible').children('.content-gal-thumbs').children('.active').children().click();
		});
	});
	
	// how to buy
	$(function(){
		var
			htb = $('#how-to-buy'),
			win = $(window);
		
		if(!htb.length) return;
		var links = htb.find('.q').children().click(function(){
			$(this).closest('td').toggleClass('txt-open');
			win.resize();
			return false;
		});
	});
	
	// panorama
	$(function(){
		$('.panorama').each(function(){
			var
				pan = $(this),
				doc = $(document),
				win = $(window),
				bg = pan.children(),
				src = bg.attr('rel');
			var oImg = new Image();
			oImg.src = src;
			
			oImg.onload = function(){
				bg.css({
					position: 'relative',
					left: 0,
					height: oImg.height,
					width: oImg.width,
					backgroundImage: 'url(' + src + ')',
					backgroundRepeat: 'no-repeat'
				});
				
				var scroller = $('<div class="panorama-scroller"><div></div></div>').css({
					opacity: .6
				}).appendTo(pan);
				
				var
					pWidth = pan.width(),
					iWidth = oImg.width;

				var updatePanorama = function(e){
					var pLeft = pan.offset().left;
					bg.css('left', -(e.pageX-pLeft)/(pWidth) * (iWidth-pWidth));
				};
				
				var updateScroller = function(){
					scroller.css({
						width: pWidth*pWidth/iWidth,
						left: -parseInt(bg.css('left'))*(pWidth)/iWidth
					});
				};

				pan.mousemove(function(e){
					updatePanorama(e);
					updateScroller(e);
				});
				
				win.bind('resize.panorama', function(){
					pWidth = pan.width();
					if(pan.offset().left + pWidth > -parseInt(bg.css('left'))){
						bg.css('left', Math.min(0, pWidth- iWidth));
					}

					updateScroller();
				});
			};
		});
	});
	
	// baloons
	$(function(){
		var baloons = $('.baloon');
		
		baloons.css({
			display: 'block',
			opacity: 0
		}).mouseover(function(){
			$(this).stop().animate({opacity: 1}, 200);
		}).mouseout(function(){
			$(this).stop().animate({opacity: 0}, 200);
		});
	});
	
	//	chrome window resize bug
	setTimeout(function(){$(window).resize()}, 0);
})(jQuery);
