playlistScrollbar = Class.create({});
Object.extend(playlistScrollbar.prototype, Event.Listener);
Object.extend(playlistScrollbar.prototype, Event.Publisher);
Object.extend(playlistScrollbar.prototype, {
	options: {
		showN: 3, // Default number of items in playlist to show before adding a scrollbar
		parentContainerID: 'hero', // ID of overall container housing entire dropdown module, default: #hero
		scrollbarWidth: 20, // The width of the space needed to fit the scroll bar
		dropdowns: '.dropdown-list ul', // Used to fix positioning of dropdowns after scrolling offset (doesn't affect FF)
		lastItemOffset: 98, // How far down is the trigger button from the top of the list item in px?
		pliHeight: 145, // Maximum height for 1 list item, fallback if stylesheet did not load in time
		arrows: true // Have up/down scrolling arrows?
	},

	initialize: function(playlistItems, playlistContainer, options) {
		if(!options) options = {};
		Object.extend(this.options,options);

		this.options.dropdowns = $$(this.options.dropdowns);

		this.plis = playlistItems;
		this.plisN = this.plis.length;
		
		//this.options.showN = this.calcShowN();
		
		// If scroll bar is needed, build it
		if(this.plisN>this.options.showN) this.setStage(playlistContainer);
	},
	
	calcShowN: function(){
		
		parentContainer = $(this.options.parentContainerID);
		availableY = parentContainer.getHeight() + parentContainer.cumulativeOffset()[1] - this.pliContainer.cumulativeOffset()[1];
		console.log(parentContainer);
		console.log(parentContainer.getDimensions());
		console.log(availableY);

		availableY

		for (i = 1; availableY >= this.pliHeight; availableY -= this.pliHeight, i++)
				
		return i;
	},

	setStage: function(playlistContainer){
		hasScrollbar = true;
		
		this.lastScrollState = 0;

		this.pliContainer = playlistContainer;
		this.pliParent = this.pliContainer.up();
		this.pliParentParent = this.pliParent.up();

		this.pliHeight = this.plis[0].getHeight();
		if(this.pliHeight > this.options.pliHeight) this.pliHeight = this.options.pliHeight; // Fix for slower connections (shouldn't be an issue, but this is a fallback)

		this.pliContainerHeight = this.options.showN*this.pliHeight;

		scrollContentHeight = this.pliContainer.getHeight();
		scrollContainerHeight = this.pliContainerHeight;

		this.pliContainer.setStyle({'height': this.pliContainerHeight+'px', 'paddingRight': this.options.scrollbarWidth+'px', 'overflowY':'hidden'});

		this.pliParentParent.addClassName('scrolling');
		
		this.pliLast = this.plisN-1;
		
		this.createScrollbar();
		this.updateDropdowns();
	},

	createScrollbar: function(){
		if(this.options.arrows) height = (this.pliContainerHeight-53);
		else height = (this.pliContainerHeight-33);
		this.scrollbarTrack = new Element('div',{'class':'scrollbar scrollbar-track', 'style':'height: '+height+'px;'});
		this.scrollbarHandle = new Element('div',{'class':'scrollbar scrollbar-handle'});
		this.scrollbarTrack.insert(this.scrollbarHandle);
		this.pliParent.insert(this.scrollbarTrack);
		
		if(this.options.arrows) {
			this.scrollbarTrack.addClassName('hasArrows');
			this.addArrows();
		}

		this.setLast(this.pliLast);
		
		this.scrollbar = new Control.ScrollBar(this.pliContainer, this.scrollbarTrack);
	},

	addArrows: function(){
		up = new Element('div', {'class':'scrollbar-arrow up'});
		down = new Element('div', {'class':'scrollbar-arrow down'});
		this.pliParent.insert(up);
		this.pliParent.insert(down);
		
		up.observe('click', function(){
			// (((Index of last showing, starting at 1) - How many to show on each page) - 1 step) * height of each list item;
			amount = (((this.pliLast + 1) - this.options.showN) - 1)*this.pliHeight;
			this.scrollbar.scrollTo(amount, true);
		}.bind(this));
		down.observe('click', function(){
			// (((Index of last showing, starting at 1) - How many to show on each page) + 1 step) * height of each list item;
			amount = (((this.pliLast + 1) - this.options.showN) + 1)*this.pliHeight;
			this.scrollbar.scrollTo(amount, true);
		}.bind(this));
	},

	updateDropdowns: function(){
		if(!AC.Detector.isFirefox()){
			this.options.dropdowns[0].setStyle({'display':'block'});
			this.defaultTop = this.options.dropdowns[0].positionedOffset()[1];
			this.options.dropdowns[0].setStyle({'display':'none'});
		}
		
		this.listenForEvent(this.scrollbar, 'scrollChange', false, function(e){
			scrollOffset = e.event_data.data;
			if(scrollOffset == null) scrollOffset = 0;
			
			if(scrollOffset != this.lastScrollState){
				this.lastScrollState = scrollOffset;

				this.setLast(this.plisN-1);

				if(!AC.Detector.isFirefox()){
					if(AC.Detector.isIE()) newTop = this.defaultTop;
					else newTop = (this.defaultTop - scrollOffset);
					this.options.dropdowns.each(function(el){
						liParent = el.up('li');
						if(liParent.hasClassName('last')) {
							if(!AC.Detector.isIE()) newTop -= 2;
							el.setStyle({'bottom':-(newTop-this.defaultTop)+'px', 'top':'auto'});
						} else {
							el.setStyle({'top':newTop+'px', 'bottom':'auto'});
						}
					}.bind(this));
				}
			}
		}.bind(this));
	},

	setLast: function(index){
		this.plis[this.pliLast].removeClassName('last');

		el = this.plis[index];
		if(!this.topReference) this.topReference = el.up().cumulativeOffset()[1];
		if(!this.bottomReference) this.bottomReference = this.topReference + scrollContainerHeight;
		
		if(!this.dropdownIsVisible(el)){ // If current .last is not visible
			el.removeClassName('last');
			this.setLast(index-1);

			return false;
		} else {
			this.pliLast = index;
			el.addClassName('last');

			return true;
		}
	},

	dropdownIsVisible: function(el){
		elTopReference = el.cumulativeOffset()[1] - el.cumulativeScrollOffset()[1] + this.options.lastItemOffset;
		//alert(elTopReference);
		
		if(elTopReference<this.bottomReference) return true;
		else return false;
	}
});

// EXCERPT FROM:
/**
 * @author Ryan Johnson <http://syntacticx.com/>
 * @copyright 2008 PersonalGrid Corporation <http://personalgrid.com/>
 * @package LivePipe UI
 * @license MIT
 * @url http://livepipe.net/core
 * @require prototype.js
 */

//mouse:wheel
(function(){
    function wheel(event){
        var delta, element, custom_event;
        // normalize the delta
        if (event.wheelDelta) { // IE & Opera
            delta = event.wheelDelta / 120;
        } else if (event.detail) { // W3C
            delta =- event.detail / 3;
        }
        if (!delta) { return; }
        element = Event.extend(event).target;
        element = Element.extend(element.nodeType === Node.TEXT_NODE ? element.parentNode : element);
        custom_event = element.fire('mouse:wheel',{ delta: delta });
        if (custom_event.stopped) {
            Event.stop(event);
            return false;
        }
    }
    document.observe('mousewheel',wheel);
    document.observe('DOMMouseScroll',wheel);
})();

