/* Спасибо, Карабоз! */
function getPageX(oElement){
	var iPosX = oElement.offsetLeft;
	while ( oElement.offsetParent != null ) {
		oElement = oElement.offsetParent;
		iPosX += oElement.offsetLeft;
		if (oElement.tagName == 'BODY') break;
	}
	return iPosX;
}

function getElementWidth(JQObject){
	var p_left = parseInt(JQObject.css('padding-left'));
	var p_right = parseInt(JQObject.css('padding-right'));
	var width = JQObject.width();
	
	return p_left+p_right+width;
}

function windowHeight() {
	var de = document.documentElement;

	return self.innerHeight || ( de && de.clientHeight ) || document.body.clientHeight;
}

//fotostrip
	
	//disable btns
	function check_btns(){
		
		var navbarWidth = getElementWidth(navbar);
		
		//get left
		if ($.browser.msie)
				var left = parseFloat(thumbs.css('margin-left'));
			else
				var left = parseFloat(thumbs.css('left'));
		
		//disable btns if needed
		var minLeft = -(numThumbs*thumbWidth) + navbarWidth;
		var maxRight = 0;
		rightBtn.css('opacity', left <= minLeft? 0.5: 1);
		leftBtn.css('opacity', left >= maxRight? 0.5: 1);
	}
	
	//scroll .thumbs
	function fstrip_scrollBy(amount){
	
		var navbarWidth = getElementWidth(navbar);
		
		//get left
		if ($.browser.msie)
				var left = parseFloat(thumbs.css('margin-left'));
			else
				var left = parseFloat(thumbs.css('left'));				
				
		newleft = left+amount;
	
		//check borders
		var minLeft = -(numThumbs*thumbWidth) + navbarWidth;
		var maxRight = 0;
		if (newleft <= minLeft) newleft = minLeft;
		if (newleft >= maxRight) newleft = maxRight;
		
		//set left
		if (Math.abs(newleft-left) <= step) { //easy advance
			if ($.browser.msie)
				thumbs.css('margin-left', newleft+"px");
			else
				thumbs.css('left', newleft+"px");
			
			check_btns();
		} else { //smooth advance
			if ($.browser.msie)
				var anim_obj={marginLeft: newleft};
			else
				var anim_obj={left: newleft};

			$('.thumbs').animate(anim_obj, 500, check_btns);
		}
	}


function show_dbox(anchor) {
	
	var link = $(anchor);

	//xek: close dbox
	//if($('div.dbox-frame-on').length)
	//	dBoxcloser();
	
	
	if(!$('div.dbox-frame').length) {
		
		// Если попап прежде не вызывался, создаём его и цепляем к BODY
		dbox = $(''+
			'<div class="dbox-frame">'+
				'<div class="wrapper">'+
					'<div class="dbox-shadow"></div>'+
					'<div class="dbox-canvas">'+
						'<div class="dbox-button"></div>'+
					'</div>'+
				'</div>'+
			'</div>').appendTo('body');
	}

	if($('div.dbox-frame').length <= 1){
		
		//scroll до низу
		offstTop = $('.fotostrip').offset().top+$('.fotostrip').height()+10-windowHeight();
		if (offstTop < 0) offstTop=0;
		availVisibleSize = $('.fotostrip').offset().top-offstTop; //windowHeight()-$('.fotostrip').height();
		$.scrollTo(offstTop, 800);
				
		// Клонируем попап, прицепляем клон к BODY и показываем его
		var frame = dbox.clone().appendTo('body').addClass('dbox-frame-on');
		
		//xek: высота = видимая пустая область
		//var fotostripOffset = $('.fotostrip').offset();
		frame.css('top', offstTop+'px');
		frame.css('height', availVisibleSize+'px');
		//frame.css('background', 'yellow');
		$('.wrapper', frame).css('height', availVisibleSize+'px');
	
	
		var shadow = frame.find('div.dbox-shadow').animate({opacity:0.6}, 300);
		var canvas = frame.find('div.dbox-canvas');
		var button = frame.find('div.dbox-button');
	
		// Цепляем к попапу картинку и ждём её загрузки
		var image = $('<img src="'+ link.attr('href') +'" alt="'+ link.attr('title') +'"/>');
	
		image.appendTo(canvas);
		
		image.load(function(){
			var imageWidth = image.width();
			var imageHeight = image.height();
			var frameWidth = frame.width()-40;
			var frameHeight = frame.height()-40;
	
			// Вписываем картинку в размер окна, если она шире, чем окно
			if(imageWidth > frameWidth) {
	
				imageWidth = frameWidth;
				image.width(imageWidth);					
				while(image.height() > frameHeight) {
					image.width(imageWidth);
					imageWidth--;
				}
	
				imageHeight = image.height();
			}
	
			// Вписываем картинку в размер окна,
			// если она выше, чем окно
			if(imageHeight > frameHeight) {
	
				imageHeight = frameHeight;
				image.height(imageHeight);						
				while(image.width() > frameWidth) {
					image.height(imageHeight);
					imageHeight--;
				}
	
				imageWidth = image.width();
			}
	
			
			// Анимируем загрузчик до размеров картинки и одновременно смещаем к центру
			canvas.addClass('dbox-canvas-load').animate({
	
				width: imageWidth,
				marginLeft: -imageWidth/2,
				height: imageHeight,
				marginTop: -imageHeight/2
	
			}, 500, function() {
	
				// После завершения анимации показываем кнопку и картинку
				canvas.addClass('dbox-canvas-done');
				button.addClass('dbox-button-on');
				button.addClass(navigator.platform.toLowerCase().indexOf('mac')+1?'dbox-button-left':'dbox-button-right');
	
				image.animate({opacity:1}, 500, function() {
	
					// Вешаем обработчики закрытия
					shadow.click(dBoxcloser);
					button.click(dBoxcloser);
	
				});
			});			
		});
	
	
	} else { //dbox уже есть и виден

		var frame = $('.dbox-frame:last');
		var shadow = frame.find('div.dbox-shadow').animate({opacity:0.6},300);
		var canvas = frame.find('div.dbox-canvas');
		var button = frame.find('div.dbox-button');
		var image = frame.find('img');
		
		//if (window.hiddenDiv) alert(hiddenDiv.parent());// && hiddenDiv.parent().is('body')) alert(1);
		
		// Цепляем к попапу картинку и ждём её загрузки
		if (!window.hiddenDiv)
			hiddenDiv = $('<div style="position:absolute;top:0;left:0;width:0;height:0;z-index:1;visibility:hidden;"></div>');
		newImage = $('<img src="'+ link.attr('href') +'" alt="'+ link.attr('title') +'"/>');
	
		//newImage.css('display', 'none');
		hiddenDiv.appendTo('body');
		newImage.appendTo(hiddenDiv);
		
		newImage.load(function(){
			var imageWidth = newImage.width();
			var imageHeight = newImage.height();
			var frameWidth = frame.width()-40;
			var frameHeight = frame.height()-40;
	
			// Вписываем картинку в размер окна, если она шире, чем окно
			if(imageWidth > frameWidth) {
	
				imageWidth = frameWidth;
				newImage.width(imageWidth);					
				while(newImage.height() > frameHeight) {
					newImage.width(imageWidth);
					imageWidth--;
				}
	
				imageHeight = newImage.height();
			}
	
			// Вписываем картинку в размер окна, если она выше, чем окно
			if(imageHeight > frameHeight) {
	
				imageHeight = frameHeight;
				newImage.height(imageHeight);						
				while(newImage.width() > frameWidth) {
					newImage.height(imageHeight);
					imageHeight--;
				}
	
				imageWidth = newImage.width();
			}
			
			//fadeout
			$.browser.msie? button.hide(): button.animate({opacity:0}, 500);
			image.animate({opacity:0}, 500, function(){
				
				// Анимируем загрузчик до размеров картинки и одновременно смещаем к центру
				canvas.addClass('dbox-canvas-load').animate({
		
					width: imageWidth,
					marginLeft: -imageWidth/2,
					height: imageHeight,
					marginTop: -imageHeight/2
		
				}, 500, function() {
					$.browser.msie? button.show(): button.animate({opacity:1}, 500);
					//switch img
					image.remove();
					newImage.remove().appendTo(canvas);
					newImage.animate({opacity:1},500);
					image = newImage;
					hiddenDiv.remove();
				});
			});
			
			/*//Загрузчик по размеру картинки и одновременно смещаем к центру
			canvas.css('width', imageWidth);
			canvas.css('height', imageHeight);
			canvas.css('background-color', 'transparent');
			
			
			// После завершения анимации показываем кнопку и картинку
			canvas.addClass('dbox-canvas-done');
			button.addClass('dbox-button-on');
			button.addClass(navigator.platform.toLowerCase().indexOf('mac')+1?'dbox-button-left':'dbox-button-right');
	
			image.animate({opacity:1}, 500, function() {
								
				// Вешаем обработчики закрытия
				shadow.click(dBoxcloser);
				button.click(dBoxcloser);
				
				//canvas
				canvas.css('background-color', '#000');
				$('div.dbox-frame-on:first').remove();
			});*/
		});
	}
	
	
	// Функция закрытия попапа
	dBoxcloser = function() {

		canvas.remove();
		shadow.animate({opacity:0},300,function() {
			frame.remove();
		});
	}

	// Внимательно слушаем клавишу Esc
	$(document).keydown(function(e) {
		if(e.which==27) dBoxcloser();
	});

	return false;
}
	
	
	
$(function(){
		
//fotostrip

	//vars
	navbar = $('.fotostrip .navbar');
	thumbs = $('.fotostrip .thumbs');
	interval = 0; //resource
	numThumbs = $('.fotostrip .thumbs a').length;
	thumbWidth = getElementWidth($('.fotostrip .thumbs a:first'));
	leftBtn = $('.fotostrip .content .left a');
	rightBtn = $('.fotostrip .content .right a');
	step = 5;
	
	
	//scroll btns - click
	$('.fotostrip .content .left a, .fotostrip .content .right a').click(function(){
		var is_left = $(this).parent().hasClass('left');
		fstrip_scrollBy(is_left? thumbWidth: -thumbWidth);
		return false;
	});


	//scroll btns - mouse down	
	/*$('.fotostrip .content .left a, .fotostrip .content .right a').mousedown(function(){
		var is_left = $(this).parent().hasClass('left');
		interval = setInterval(function(){fstrip_scrollBy(is_left? step: -step)}, 25);
		return false;
	});
	
	
	//scroll btns - mouse up
	function unbind_scroll_btns(){	
		window.clearInterval(interval);
		return false;
	}
	$('.fotostrip .content .left a, .fotostrip .content .right a').mouseup(unbind_scroll_btns).mouseout(unbind_scroll_btns);*/
	
	
	//thumb - click
	$('.fotostrip .thumbs a').click(function(e){
		
		show_dbox(this);
				
		//advance scroll if <A> clicked is last entirely visible
		var clickX = e.clientX - getPageX(navbar[0]);
			
			var navbarOffset = navbar.offset();
			var thumbOffset = $(this).offset();
			var navbarWidth = getElementWidth(navbar);
			var borderRight = navbarWidth - 2*thumbWidth;
			var borderLeft = thumbWidth;
			var thumb_navbar_pos = thumbOffset.left - navbarOffset.left;
			
			if (thumb_navbar_pos > borderRight) {//clicked <A> is last entirely visible
				fstrip_scrollBy(-thumbWidth);
			}
			
			//alert(thumb_navbar_pos - borderLeft);
			if (thumb_navbar_pos < borderLeft) {
				fstrip_scrollBy(thumbWidth);
			}
		
		return false;
	});
	
	
	
	//enable
	$('.fotostrip').addClass('enabled');
	check_btns();
	
});











				
				
				
							
			
			

				
				
				
				
				
				
				