var FlexcrollMemory = Class.create({
	
	// Expects to live inside a "dom:loaded"-event
	initialize : function() {
		this.scrollers = $$('.flexcroll');
		if (this.scrollers.length == 0) return;
		this.href = document.location.href;
		this.updateScrollers(); 
		setInterval(this.savePosition.bind(this), 1000);
		this.readyToSave = true;
	},
	
	updateScrollers : function() {
		if (window.flexcrollPositions) {
			window.flexcrollPositions.each(function(scroller) {
				var scrollerDiv = $(scroller.id);
				if (!scrollerDiv) return;
				var position = scroller.position;
				if (scrollerDiv.hasClassName('flexcrollactive')) {
					scrollerDiv.contentScroll(0, position, false);
				} else {
					scrollerDiv.scrollTop = position;
				}
			}.bind(this))
		}
	},
	
	savePosition: function() {
		if (!this.readyToSave) return;
		this.readyToSave = false;
		var data = this.getData();
		new Ajax.Request('/flexcroll_save_pos', {
			parameters : {
				scrollers	: data.toJSON(),
				href  		: this.href
			},
			method		: 'post',
			onSuccess : this.ajaxReturn.bind(this),
			onFailure : this.ajaxReturn.bind(this)
		});
	},
	
	ajaxReturn : function() {
		this.readyToSave = true;
	},
	
	getData : function() {
		var data = [];
		this.scrollers.each(function(scroller) {
			data.push({id : scroller.id, position: this.getScrollPosition(scroller.id)})
		}.bind(this));
		return data;
	},
	
	getScrollPosition : function(id) {
		if (!$(id)) return 0;
		if ($(id).hasClassName('flexcrollactive')) {
			return -($(id).down('.contentwrapper').positionedOffset().top - removePx($(id).getStyle('paddingTop')));
		} else {
			return $(id).scrollTop;
		}
	}
});

var flexcrollMemory;
Event.observe(document, 'dom:loaded', function() {
	//flexcrollMemory = new FlexcrollMemory();	
})

function removePx(str) {
	if (str.substring(str.length - 2) == 'px') {
		return parseInt(str.substring(0,str.length - 2), 10);
	} else {
		return parseInt(str, 10);
	}
}

