/* mouse wheel scroll */
	var hoverscroll = undefined;
	function handlewheel(delta) {
		if (hoverscroll) hoverscroll.scrolltodelta(delta);
	}
	
	function wheel(event){
        var delta = 0;
        if (!event) event = window.event; // Событие IE.
        // Установим кроссбраузерную delta
        if (event.wheelDelta) { 
                // IE, Opera, safari, chrome - кратность дельта равна 120
                delta = -event.wheelDelta/120;
        } else if (event.detail) { 
                // Mozilla, кратность дельта равна 3
                delta = event.detail/3;
        }
        // Вспомогательня функция обработки mousewheel
        if (delta && typeof handlewheel == 'function') {
                handlewheel(delta);
                // Отменим текущее событие - событие поумолчанию (скролинг окна).
                if (event.preventDefault)
                        event.preventDefault();
                event.returnValue = false; // для IE
        }
	}
	
	function setwheelhandler() {
		// Инициализация события mousewheel
		if (window.addEventListener) // mozilla, safari, chrome
		    window.addEventListener('DOMMouseScroll', wheel, false);
		// IE, Opera.
		window.onmousewheel = document.onmousewheel = wheel;
	}
/* end of mouse wheel scroll */


	function scrolltobevisible($pane, $elem) {
		var dontscroll = true;
		var desiredscroll = 0;
		
		if ($elem.offset().top < $pane.offset().top) {
			dontscroll = false;
			desiredscroll = $elem.offset().top - $pane.offset().top - 4;
		} else if ($elem.offset().top + $elem.height() >= $pane.offset().top + $pane.height()) {
			dontscroll = false;
			desiredscroll = ($elem.offset().top + $elem.height()) - ($pane.offset().top + $pane.height()) + 4;
		}
		
		if (!dontscroll) {
			var desiredscrollpos = $pane.scrollTop() + desiredscroll;
			if (desiredscrollpos < 0) desiredscrollpos = 0;
			if (desiredscrollpos > $pane[0].scrollHeight) desiredscrollpos = $pane[0].scrollHeight;
			
			if ($pane[0].myscroll != undefined)
				$pane[0].myscroll.scrollto(desiredscrollpos, true, true);
		}
	}
	
	function makescroller($pane, $horizoffset, $scrollerheight) {
		var $scrollbar = $('<div class="scrollbar"><div class="scrollbg"><div class="scroller"></div></div></div>').insertAfter($pane);
		var $scroller = $('.scroller', $scrollbar);
		var $scrollbg = $('.scrollbg', $scrollbar);
		var $paneinner = $pane.children();
		
		$pane.css('overflow', 'hidden');
		
		$scrollbar.css('height', $pane.height() + 'px');
		$scrollbg.css('height', $pane.height() + 'px');
		$scrollbar.css('top', ($pane.position().top) + 'px');
		$scrollbar.css('left', ($pane.position().left + $horizoffset) + 'px');
			
		$scroller.css('height', $scrollerheight);

		$scrollbar.show();
		
		var scrollobj = { 
			mousestate: 0,
			scrollbar: $scrollbar,
			scroller: $scroller,
			scrollerheight: $scrollerheight,
			scrollmax: $pane.height() - $scrollerheight,
			pane: $pane,
			panemin: 0,
			panemax: 0,
			panepos: 0,
			wheelstep: 30,
			
			update: function() {
				this.panemax = this.pane[0].scrollHeight - this.pane.height();
				if (this.panemax < 0) this.panemax = 0;
//				this.scrollto(0, false);
			},

			interact: function(event, anim) { //process mouse event and call scroll
				var clickposy = event.pageY - this.scrollbar.offset().top;
				var desiredpos = Math.floor(clickposy - this.scrollerheight / 2);
				this.scrollto(desiredpos, anim);
			},
			
			scrolltodelta: function(deltapos) {
				var desiredpos = this.panepos += deltapos * this.wheelstep;
				if (desiredpos < this.panemin) desiredpos = this.panemin;
				if (desiredpos >= this.panemax) desiredpos = this.panemax - 1;
				this.scrollto(desiredpos, false, true);
			},
			
			scrollto: function(pos, anim, thatspanepos) { //panepos optional
				var desiredpos = thatspanepos? Math.floor(pos / this.panemax * this.scrollmax): pos;

				if (desiredpos < 0) desiredpos = 0;
				if (desiredpos >= this.scrollmax) desiredpos = this.scrollmax - 1;

				this.panepos = thatspanepos? pos: Math.floor(desiredpos / this.scrollmax * this.panemax);
					
				if (anim) {
					this.scroller.stop().animate({ top: desiredpos + 'px' }, 150);
					this.pane.stop().animate({scrollTop: this.panepos}, 150);
				} else {
					this.scroller.stop().css('top', desiredpos + 'px');
					this.pane.stop().scrollTop(this.panepos);
				}
			}
		};
		
		scrollobj.update();
		
		$pane[0].myscroll = scrollobj;

		$pane.hover(function() {
			hoverscroll = this.myscroll;
		}, function() {
			hoverscroll = undefined;
		});
		
		$scrollbar.mousedown(function(event) {
			scrollobj.interact(event, 1);
			scrollobj.mousestate = true;
			event.preventDefault();
		});

		$('body').mouseup(function(event) {
			if (scrollobj.mousestate)
				scrollobj.interact(event, 0);
			scrollobj.mousestate = false;
			event.preventDefault();
		}).mousemove(function(event) {
			if (scrollobj.mousestate)
				scrollobj.interact(event, 0);
			event.preventDefault();
		});
	}

$(function() {
	//fix menu spaces
	var menuwidthsum = 0, menucount = 0;
	$('#menu a').each(function() { menucount++; menuwidthsum += $(this).width(); });
	var marginright = Math.floor(($('#menu').width() - 2 - menuwidthsum) / (menucount - 1));
	$('#menu a').css('margin-right', marginright + 'px');
	
/*about*/
	if ($('.wrap-about').length == 1) {
		makescroller($('.cont-scroll'), -30, 107);
		makescroller($('.photogal-scroll'), 375, 107);
	}

/*works*/
	if ($('.wrap-works').length == 1) {
		function works_updateactive() {
			$('.wrap-works .wlistitem a img').each(function() {
				if ($(this).hasClass('active')) this.src = this.srcac;
				else this.src = this.srcia;
			});
		}
		
		makescroller($('.wlist-scroll'), 143, 83);
		
		$('.wlistitem a img').each(function() { 
			var srcia = this.src;
			var srcac = this.src.replace('works-bw-', 'works-sm-');
			var srcb = this.src.replace('works-bw-', 'works-');

			var im1 = new Image(); im1.src = srcac;
			var im2 = new Image(); im2.src = srcb;

			this.srcia = srcia;
			this.srcac = srcac;
			this.srcb = srcb;
		});

		works_updateactive();	
	
		$('.wlistitem a img').hover(
			function() {
				if (!$(this).hasClass('active'))
					this.src = this.srcac;
			},
			function() {
				if (!$(this).hasClass('active'))
					this.src = this.srcia;
			}
		);

		$('.wlistitem a').click(function() {
			$('.preview img.disp').attr('src', $('.preview img.fade').attr('src')).show();
			$('.preview img.fade').hide();
		
			$('.wlistitem a img.active').removeClass('active');

			var srcb = '';	
			var altb = '';
			$('img', this).addClass('active').each(function() {
				srcb = this.srcb; 
				altb = this.alt;
			});
		
			works_updateactive();

			$('.preview img.fade').attr({ src: srcb, alt: altb, title: altb}).fadeIn('slow');
		
			return false;
		});
	}
	
/*portfolio*/
	if ($('.wrap-portfolio').length == 1) {
		function portfolio_updateactive() {
			$('.wrap-portfolio .plistitem a img').each(function() {
				if ($(this).hasClass('active')) this.src = this.srcac;
				else this.src = this.srcia;
			});
		}

		var $catl2scroll = $('.catl2-scroll');
		var $catl2holder = $('.catl2-scroll > .holder');
		if ($catl2scroll.height() <= $catl2holder.height())
			makescroller($catl2scroll, -30, 83);
/*		else
			$catl2scroll.css('padding-top', $catl2scroll.height() - $catl2holder.height());*/
			
//		alert($catl2scroll[0].scrollHeight - $catl2scroll.height());

		if ($('.plist-scroll').length > 0)
			makescroller($('.plist-scroll'), 143, 83);

		$('.plistitem a img').each(function() { 
			var srcia = this.src;
			var srcac = this.src.replace('portfolio-bw-', 'portfolio-sm-');
			var srcb = this.src.replace('portfolio-bw-', 'portfolio-');

			var im1 = new Image(); im1.src = srcac;
			var im2 = new Image(); im2.src = srcb;

			this.srcia = srcia;
			this.srcac = srcac;
			this.srcb = srcb;
		});

		portfolio_updateactive();	
	
		$('.plistitem a img').hover(
			function() {
				if (!$(this).hasClass('active'))
					this.src = this.srcac;
			},
			function() {
				if (!$(this).hasClass('active'))
					this.src = this.srcia;
			}
		);

		$('.plistitem a').click(function() {
			$('#overdiv').html($('em', this).html());
		
			$('.preview img.disp').attr('src', $('.preview img.fade').attr('src')).show();
			$('.preview img.fade').hide();
		
			$('.active').removeClass('active');
//			$('.plistitem a img.active').removeClass('active');
		
			var $thisimg = $('img', this);
			
			$('#' + rels.pc[$thisimg.attr('id')]).addClass('active');
			
			var $loc = $('#' + rels.pl[$thisimg.attr('id')]);
			$loc.addClass('active');
			
			$('.plistitem').hide();
			
			for (var i = 0; i < rels.lpa[$loc.attr('id')].length; i++)
				$('#' + rels.lpa[$loc.attr('id')][i]).parent().show();
			
			$('.plist-scroll')[0].myscroll.update();
				
			scrolltobevisible($('.catl2-scroll'), $loc);
			scrolltobevisible($('.plist-scroll'), $thisimg);

			var srcb = '';	
			var altb = '';
			$thisimg.addClass('active').each(function() {
				srcb = this.srcb;
				altb = this.alt;
			});
		
			portfolio_updateactive();

			$('.preview img.fade').attr({ src: srcb, alt: altb, title: altb}).fadeIn('slow');
		
			return false;
		});
		
		$('.catl2 a.place').click(function() {
			$('#' + rels.cp[$(this).attr('id')]).click();
		});
		
		$('.catl2 a.loc').click(function() {
			$('#' + rels.lp[$(this).attr('id')]).click();
		});
		
		$('.plistitem a').first().click();
		
		$('.preview').hover(function() {
		}, function() {
			$('#overdiv').hide();
		}).mousemove(function(event) {
			var $overdiv = $('#overdiv');
			$overdiv.show();
			var posx = Math.floor(event.pageX - $overdiv.width() / 2);
			$overdiv.offset({ left: posx, top: event.pageY + 30 });
		});
	}

	setwheelhandler()
});
	
