ScrollPanel = new Class({
	// Default Options.
	options: {
		contentDiv: 'homebox',
		outerDiv: 'homeitems',
		innerDiv: 'slider',
		panelClass: 'block',
		linkClass: 'panellink',
		currentLinkClass: 'current',
		currentPanelClass: 'currentpanel',
		lifeOfItsOwn: true,
		refreshRate: 4000,
		scrollDuration: 'normal',
		scrollTransition:'elastic:out',
		useConsole: true
	},
	// Reference Array.
	panels:Array(),
	initialize: function(options) {
		// Set the Options.
		this.setOptions(options);
		try {
			// Get the Container, Panels and Tabs as Class properties..
			ScrollPanel.container = $(this.options.innerDiv);
			ScrollPanel.panels = $$('#' + this.options.contentDiv + ' .' +  this.options.panelClass);
			ScrollPanel.tabs  = $$('#' + this.options.contentDiv + ' .' +  this.options.linkClass);
            
            //set the width of the tabs if it is 3 or 4.            
             if(ScrollPanel.tabs.length == 4) {
                ScrollPanel.tabs.getFirst('a').each(function(el){
                   el.setStyle('width',148);
                   ScrollPanel.tabs.setStyle('width',258);
                });
             }
             
             
			// Get the Width of the 1st Panel.
			ScrollPanel.paneldimension = this.getPanelDimension();
			// Get Start position.
			ScrollPanel.panelposition = this.getCurrentPosition();
			// Set Start Position as our Margin.
			ScrollPanel.startmargin = ScrollPanel.panelposition;

			// Loop thru our Panels.
			ScrollPanel.panels.each(function(panelEl,i) {
                // Set the width?
               
                
				// For each Panel we will set a few things as Properties.

				// Work out each Panel's offset by using its index as a modifiier.
				var ppos  = -((ScrollPanel.startmargin + ScrollPanel.paneldimension) * i);
				// Set as Prop.
				panelEl.pos = ppos;
				// Set Index as Prop.
				panelEl.index = i;

				// Get the corresponding Tab.
				var ta = ScrollPanel.tabs[i];
				
				// Add the activeTab and showPanel Methods.
				ta.addEvent("click", this.showPanel.bindWithEvent(this, panelEl));

				// If the option is set, use periodical to flick between panels.
				if(this.options.lifeOfItsOwn) {
					// Add our own event that we can call whenever we need to change the panel on the fly.
					ta.addEvent("calledpanel", this.showPanel.bindWithEvent(this, panelEl));

                    var mainpanel = $(this.options.contentDiv);
                    mainpanel.addEvent("mouseleave", this.beginPeriodical.bindWithEvent(this));
                    mainpanel.addEvent("mouseenter", this.pausePeriodical.bindWithEvent(this));

				}

				// Set the Tab as a property of the Panel.
				panelEl.tab = ta;

			}, this);

			if(this.options.lifeOfItsOwn) {	
				ScrollPanel.interval = this.beginPeriodical();
			}

			// Set Start Panel.
			ScrollPanel.current_panel = ScrollPanel.panels[0].id;
			ScrollPanel.next_panel = false;			
			

		} catch(err) {
			if(this.options.useConsole) { console.log(err); }
		}

    },
    periodicScroll:function() {
			// Get hold of the panel - random for testing.			
			var stopPeriodical = false;
			if ( $(ScrollPanel.current_panel).getFirst('.youtube') ) {
				var youtubeState = $(ScrollPanel.current_panel).getFirst('.youtube').getFirst('object').getPlayerState();
				if (youtubeState == 1 || youtubeState == 3) {
					stopPeriodical = true;
				}
			} else {
				stopPeriodical = false;	
			}
			
			
			var nextIndex = $(ScrollPanel.current_panel).index + 1;
			var len = ScrollPanel.panels.length;

			if(nextIndex == len) {
				nextIndex = 0;
			}

			var nextPanel = ScrollPanel.panels[nextIndex];

			if(nextPanel && nextPanel.tab) {
				if ( stopPeriodical == false ) {
					nextPanel.tab.fireEvent('calledpanel');
				}
			}
    },
    beginPeriodical:function() {
        //console.log("begin");
            this.resetPeriodical();
			var myRefreshRate = this.options.refreshRate;
			ScrollPanel.interval = this.periodicScroll.periodical(myRefreshRate);
			return ScrollPanel.interval;
    },
    pausePeriodical:function() {
            //console.log("pause");
			return this.resetPeriodical();
    },
    resetPeriodical:function() {
			return $clear(ScrollPanel.interval);
    },
	activeTab:function() {
		try {
			var targ = $(ScrollPanel.current_panel.tab).getFirst();
			// Loop thru all Tabs and remove the 'current' css class.
			ScrollPanel.tabs.each(function(linkEl) {
				var l = linkEl.getFirst();
				// remove morph.
				l.removeClass(this.options.currentLinkClass);
			}, this);
			// Swap for morph.
			targ.addClass(this.options.currentLinkClass);
		} catch(err) {
			if(this.options.useConsole) { console.log(err); }
		}
		// Reset the peridiocal onclick as well. 
		// this.pausePeriodical();
		// this.beginPeriodical();
    },
    showPanel:function(event, panel) {
		try {

			if(event) {
				event = new Event(event).stop();
			}			
		
			if ($(ScrollPanel.current_panel).getFirst('div').hasClass('youtube') ) {
				try { 
					videoObject = $(ScrollPanel.current_panel).getFirst('div').getFirst('object');				
					if ( videoObject.getPlayerState() == 1 || videoObject.getPlayerState() == 3 ) {					
						videoObject.stopVideo();	
					}
				} catch (e) { return false};
			}
			

			// When we Initialised the Class we looped the Panels and set their offset as a Property.
			var newposition = panel.pos;

			// Update to the new position.
			ScrollPanel.panelposition = newposition;
			ScrollPanel.current_panel = panel;

			this.activeTab();

			var myDuration = this.options.scrollDuration;
			var myTransition = this.options.scrollTransition;

			// Set an Effect on the margin-left of the container <div>.
			// var slider = new Fx.Tween(ScrollPanel.container, 'margin-left', { 'duration':'normal','transition':'elastic:out'});
			var slider = new Fx.Tween(ScrollPanel.container, { 'duration':'normal','transition':'linear'});
			slider.start('margin-left', newposition);
		
			//slider.start(newposition);

		} catch(err) {
			if(this.options.useConsole) { console.log(err); }
		}

	},
	getCurrentPosition: function(panel) {
		if(!panel) {
			var pos =  (ScrollPanel.container) ? ScrollPanel.container.getStyle('marginLeft').toInt() : 0;
		} else {
			var pos = $(panel) ? $(panel).getStyle('marginLeft').toInt() : 0;
		}
		return pos;
	},
	getPanelDimension:function() {
		if((ScrollPanel.panels) && (ScrollPanel.panels.length > 0) && (!ScrollPanel.panelDimension)) {
			var panel = ScrollPanel.panels[0];
			ScrollPanel.panelDimension = panel.getStyle('width').toInt();
		}
		return (ScrollPanel.panelDimension) ? ScrollPanel.panelDimension : 0; 
	}
});

// Extend the Scrollpanel Class with the options Class.  
ScrollPanel.implement(new Options());

// Add the Class init to the DomReady signal.
window.addEvent('domready', function() {

 /*

    OPTIONS
   ---------

    @scrollDuration - short,normal,long or numeric.
    @scrollTransition - there are loads in the manual, here are a few:

    'quint:in:out'
    'sine:out'
    'expo:in'
    'elastic:out'
    'bounce:out'
    'linear'

    @lifeOfItsOwn - sets up the periodical if set true.
    @refreshRate - if set to lifeOfItsOwn:true, this is the pause between scrolls.

    The other options allow you to create multiple instances of scrollpanel on a page.
    Check the code, at some parts it starts its element duties from the @contentDiv option below. 

    @useConsole - is to turn on/off debug in firebug console.

 */

 var scrollPanelObj = new ScrollPanel({
	 contentDiv: 'homebox',
	 outerDiv: 'homeitems',
	 innerDiv: 'slider',
	 panelClass: 'block',
	 linkClass: 'panellink',
	 currentLinkClass: 'current',
	 currentPanelClass: 'currentpanel',
	 lifeOfItsOwn: true,
	 refreshRate: 4000,
	 scrollDuration: 'normal',
	 scrollTransition: 'expo:in:out',
	 useConsole: true
 });
 
});
