PATRIZIA = (typeof PATRIZIA != 'undefined') ? PATRIZIA : {};
(function($) {
	var scrollDuration = 500
	var fastScrollDuration = 250
	var scrollDelay = 4000

PATRIZIA.SectionAnimate = function(target, changeImg) {
	this.target = $(target)
	this.changeImg = $(changeImg)
	this.currentSection = 0;
	this.sectionCount = $('.section', this.target).size();
	this.sections = $('.section', this.target)
}
PATRIZIA.SectionAnimate.prototype.nextSection = function() {
	var oldSection = this.sections.eq(this.currentSection)
	this.currentSection++
	this.currentSection %= this.sectionCount;
	var newSection = this.sections.eq(this.currentSection)
	var lastSection = this.sections.eq(this.sections.size)
	
	this.animateActive(oldSection, newSection)
	
	$('.big-image-wrapper img', newSection)
	.clone()
	.appendTo(this.changeImg)
	.fadeTo(scrollDuration, 1, 'swing', function(){$(this).prev().remove()})
	
//	this.changeImg.attr('src', $('.big-image-wrapper img', newSection).attr('src'))
	if (this.currentSection == this.sections.size() - 1) {

	} else if (typeof scroller._scrollPane != 'undefined') {
		scroller.scrollToSection(Math.max(0, this.currentSection - 1))
	}
}
PATRIZIA.SectionAnimate.prototype.animateActive = function(oldSection, newSection) {
	newSection.addClass('active');
	
	newSection
	.css({backgroundPosition: '100% -800px'});
	newSection
	.animate(
	{backgroundPosition: '100% -' + (800 - newSection.outerHeight()) + 'px'},
	{easing: 'swing', duration: scrollDuration}
	)

	oldSection
	.css({backgroundPosition: '100% 0'});
	oldSection
	.animate(
	{backgroundPosition: '100% ' + newSection.outerHeight() + 'px'},
	{easing: 'swing', duration: scrollDuration, complete: function() {oldSection.removeClass('active');oldSection.attr('style', oldSection.attr('style').replace(/background-position[^;]+;/,''))}}
	)
//	oldSection.removeClass('active');
}

var hoverImages = []

PATRIZIA.Scroller = function(){
	var _scrollPane,
	_scrollPaneHeight,
	contentHeight,
	visibleSections = 3,
	
	_scrollBarContainer,
	_scrollBar,
	_slider,
	
	scrollAmount,
	invisibleSections,

	autoScrollInterval,
	currentSection = 0,

	scroller,
	startDragEvent = function(e, ui) {
		this.autoScrollStop()
	},
	
	dragEvent = function(e, ui) {
		this.scrollAmount = ui.position.top / (this._scrollBar.height() - this._slider.height())

		this._scrollPane.scrollTo((this.scrollAmount * 100) + '%', 0)
	},

	stopDragEvent = function(e, ui) {
		this.scrollAmount = ui.position.top / (this._scrollBar.height() - this._slider.height())
		this.invisibleSections = $('.section', this._scrollPane).size() - visibleSections
		this.scrollAmount = Math.round(this.scrollAmount * this.invisibleSections) / this.invisibleSections
		
	
		_scrollToSection.apply(this, [(Math.round(this.invisibleSections * this.scrollAmount))])
	},

	scrollBarClick = function(e) {
		this.autoScrollStop()
		var eventX = e.pageY - $(e.target).offset().top
		if (eventX < this._slider.position().top) {
			prevSection.apply(this)
		} else if (eventX > this._slider.position().top + this._slider.height()){
			nextSection.apply(this)
		}
	},

	_scrollToSection = function(n) {
		var scrollHeight = $('.section', this._scrollPane)
		.eq(n)
		.prevAll()
		.reduce(function(a, b){
			return a + $(b).outerHeight()
		}, 0)

		var totalHeight = $('.section', this._scrollPane)
		.reduce(function(a, b){
			return a + $(b).outerHeight()
		}, 0)

		this._scrollPane.scrollTo(scrollHeight, scrollDuration)

		sliderScrollTo.apply(this,[(scrollHeight / (totalHeight - this._scrollPane.height())) * (this._scrollBar.height() - this._slider.height())])
		currentSection = n
	},

	nextSection = function(wrap) {
		
		currentSection++
		this.invisibleSections = $('.section', this._scrollPane).size() - visibleSections

		currentSection = currentSection % (this.invisibleSections + 1)
		_scrollToSection.apply(this, [currentSection])
	},

	prevSection = function() {
		currentSection--
		this.invisibleSections = $('.section', this._scrollPane).size() - visibleSections

		currentSection = currentSection % (this.invisibleSections + 1)
		_scrollToSection.apply(this, [currentSection])
	},

	sliderScrollTo = function(y) {
		this._slider
		.animate({
			'top': y
		}, scrollDuration)
	},

	scrollIntoView = function(obj) {
		this._scrollPane.scrollTo(obj.prevAll().reduce(function(a, b){ return a + $(b).outerHeight()}, 0),scrollDuration)
	}
	
	
	return {
	
		scrollToSection: function(num) {
			_scrollToSection.apply(this, [num])
		},
	
		autoScrollStart: function() {
			var that = this
			this.autoScrollInterval = setInterval(function() {nextSection.apply(that)}, scrollDelay)
			this.autoScrollStopped = false
		},
		autoScrollStop: function() {
			clearInterval(this.autoScrollInterval)
			this.autoScrollInterval = undefined
			clearInterval(autoAnimate)
			autoAnimate = undefined
			this.autoScrollStopped = true
		},
		autoScrollPause: function(e) {
			var that = this
			clearInterval(this.autoScrollInterval)
			clearInterval(autoAnimate)
			hoverImages.push(
			$('.big-image-wrapper img', e.target)
			.clone()
			.appendTo(sectAnim.changeImg)
			.fadeTo(fastScrollDuration, 1, 'swing', function(){
				if (hoverImages.length > 1) {
					
					var temp = hoverImages.pop(); 
					
					$(hoverImages).remove()
					hoverImages.push(temp);
				}
			})
			.get(0)
			)
			
		},
		autoScrollResume: function() {
			var first = $(hoverImages.pop())
			first.stop().fadeTo(fastScrollDuration, 0, 'swing', function(){$(this).remove()})
			
			$(hoverImages).remove()
			
			
			if (typeof this.autoScrollInterval != 'undefined') {
				var that = this
				this.autoScrollInterval = setInterval(function() {nextSection.apply(that)}, scrollDelay)
			}
			if (typeof autoAnimate != 'undefined') {
				var that = this
				autoAnimate = setInterval(sectAnim.nextSection.applyWith(sectAnim), scrollDelay)
			}
		},
		createScroller: function(scrollPane, afterDrag) {
			
			var scroller = this
			this._scrollPane = _scrollPane = scrollPane
			this._scrollBarContainer = _scrollBarContainer = $('<div class="scroll-bar-container">')
			_scrollPane.parent().append(_scrollBarContainer)

			this._scrollBar = _scrollBar = $('<div class="scroll-bar">')
			_scrollBarContainer.append(_scrollBar)

			_scrollPane.parent().width(_scrollPane.parent().width() + _scrollBarContainer.outerWidth())

			_scrollBar.append($('<div class="top" /><div class="middle" /><div class="bottom" /> '));
			this._slider = _slider = $('<div class="slider">');
			_scrollBar.append(_slider);

			_slider
			.draggable({ 
				axis: 'y', 
				containment: 'parent',
				start: startDragEvent.applyWith(scroller),
				drag: dragEvent.applyWith(scroller),
				stop: ((afterDrag === true) ? stopDragEvent.applyWith(scroller) : null)
			})


			_scrollBar.click(scrollBarClick.applyWith(scroller))
			_slider.click(function(e){e.stopPropagation()})


		}
	}
}

$(document)
.ready(function() {
	//scroller
	var context = $('#scroll-frame');
	var scrollPane = $('.scroll-pane', context)
	
	var scrollPaneHeight  = scrollPane
		.height()
	var contentHeight = $('.section', scrollPane)
		.reduce(function(a, b){
			return a+$(b).outerHeight()
		},0)
	
		scroller = new PATRIZIA.Scroller()
	if (contentHeight > scrollPaneHeight) {
		scroller.createScroller(scrollPane, true)
		
		//scroller.autoScrollStart()
		//autoScrollInterval = setInterval(nextSection, scrollDelay)
	} else {
	}
	
	$('.section', scrollPane)
	.bind('mouseenter', {'src':scroller}, function(e){
		var target = e.target
		
		target = $(target).hasClass('section') ? $(target) : $(target).closest('.section', _scrollPane)
		e.target = target[0]
		e.data.src.autoScrollPause.apply(e.data.src, [e])
	})
	scrollPane
	.bind('mouseleave', {'src':scroller}, function(e){
		e.data.src.autoScrollResume.apply(e.data.src, [e])
	})
	
	
	sectAnim = new PATRIZIA.SectionAnimate('#scroll-frame .scroll-pane', '#content-top-bg')
	autoAnimate = setInterval(sectAnim.nextSection.applyWith(sectAnim), scrollDelay)
})
})(jQuery);

