var TickerTape = new Class({
	
	Implements: [Options,  Events],
	
	options: {
		itemDuration:	1000,		// length of time between items
		scrollSpeed: 	2000,		// scroll speed
		showControls: true,
		transition: 'linear'		// transition type to use
	},
	
	baseId: null,
	
	container: null,
		
	currentItem: -1,
	
	transition: null,
	
	items: [],
	
	paused: true,
	
	timer: null,
	
	initialize: function(container, options) {		
		this.setOptions(options);
		this.container = $(container);
		
		this._setup();
	},
		
	addItem: function(category, itemTitle, itemLink) {
		this.items.extend([['item', category, itemTitle, itemLink]]);
	},

        addNode: function(category, element) {
                this.items.extend([['node', category, element]]);
        },
	
	hasItems: function() {
		return (this.items.length > 0)?true:false;
	},
	
	nextItem: function() {				
		// jump back to start when we run out of items
		if (this.currentItem >= (this.items.length - 1)) {
			this.currentItem = -1;
		}
		
		this._showItem(++this.currentItem);
	},
	
	previousItem: function() {		
		// jump to end when we run out of items
		if (this.currentItem <= 0) {
			this.currentItem = this.items.length;
		}
		
		this._showItem(--this.currentItem);
	},

	start: function() {		
		// any items to loop through?
		if (this.items.length > 0) {
			this.paused = false;
						
			// start the ticker tape immediately
			this.nextItem();
						
			// finally change status and text of stop / start control
			this._updateControls('stop');
		}
	},
	
	stop: function() {
		// is this currently playing
		if (!this.paused) {		
			// cancel current animation
			this.transition.cancel();
			$(this.baseId + 'Item').getFirst().setStyle('left', 0);
			
			this.paused = true;
						
			// finally change status and text of stop / start control
			this._updateControls('start');
		}
	},
	
	_showItem: function(i) {		
		// does the item to display exist?
		if (this.items[i]) {
			var categoryContainer  = $(this.container.get('id') + 'Category');
			var itemContainerWidth = $(this.baseId + 'Item').getWidth();

			// check if the category has changed
			if (categoryContainer.get('text') != this.items[i][1]) {
				$(this.baseId + 'Category').set('text', this.items[i][1]);
			}

                        // check item type
                        var textWidth = 0;
                        if (this.items[i][0] == 'item') {
                                scrollingItem = new Element('a', {
                                        'href': this.items[i][2],
                                        'title': this.items[i][1],
                                        'text':  this.items[i][1]
                                });

                                textWidth = scrollingItem.getWidth();
                        } else {
                                scrollingItem = this.items[i][2].clone();
                        }

                        scrollingItem.setStyles({'position': 'relative', 'left': itemContainerWidth});
                        $(this.baseId + 'Item').empty().adopt(scrollingItem);

                        if (0 == textWidth) {
                                scrollingItem.getElements('a').each(function (el) {
                                        textWidth += el.getWidth() + 20; // account for 5px margin + padding either side
                                });
                        }

			var scrollDistance 	= itemContainerWidth + textWidth;
			var scrollDuration	= this.options.scrollSpeed * (scrollDistance / 100);
						
			// do transition
			this.transition = new Fx.Tween(scrollingItem, {
				duration: scrollDuration,
				transition: this.options.transition,
				onComplete: (function() {
					// is the ticker tape paused?
					if (!this.paused) {
						this.nextItem.delay(this.options.itemDuration, this);
					}
				}).bind(this)
			}).start('left', '-' + textWidth + 'px');
		}
		return;
	},
	
	_setup: function() {
		this.baseId = this.container.get('id');
		
		this.container.adopt(
			// category container
			new Element('div', {
				'id': this.baseId + 'Category' 
			}),
			
			// scrolling container
			new Element('div', {
				'id': this.baseId + 'Item' 
			}),
			
			// ticker controls
			new Element('ul', {
				'id': this.baseId + 'Controls'
			}).adopt(
			new Element('li', {
					'class': 'previous'
				}).adopt(
					new Element('a', {
						'href': '#',
						'events': {
							'click': (function(e) {
								e.stop();
								
								this.stop();
								this.previousItem();
							}).bind(this)
						}
					}).adopt(
						new Element('span', {
							'text': 'Previous'
						})
					)
				),
				new Element('li', {
					'id': 'stopStart',
					'class': 'start'
				}).adopt(
					new Element('a', {
						'href': '#',
						'events': {
							'click': (function(e) {
								e.stop();
								
								if (this.paused) {
									this.start();
								} else {
									this.stop();
								}
							}).bind(this)
						}
					}).adopt(
						new Element('span', {
							'text': 'Play'
						})
					)
				),
				new Element('li', {
					'class': 'next'
				}).adopt(
					new Element('a', {
						'href': '#',
						'events': {
							'click': (function(e) {
								e.stop();
								
								this.stop();
								this.nextItem();
							}).bind(this)
						}
					}).adopt(
						new Element('span', {
							'text': 'Next'
						})
					)
				)
			)
		);
	},
	
	_updateControls: function(tickerStatus) {		
		// default to start button
		var removeClass = (tickerStatus == 'start')?'stop':'start';
		var addClass 	= (tickerStatus == 'start')?'start':'stop'
		var label 		= (tickerStatus == 'start')?'Play':'Pause'
				
		// et voila
		$(this.baseId + 'Controls').getElement('li#stopStart').removeClass(removeClass).addClass(addClass).getElement('a').getElement('span').set('text', label);
	}
});var AjaxTickerTape = new Class({
	
	Extends: TickerTape,
	
	Implements: Options,
	
	options: {
		url: null
	},
	
	initialize: function(container, options) {		
		this.parent(container, options);
		this._getAjaxItems();
	},
	
	_getAjaxItems: function() {
		new Request.JSON({
			url: this.options.url,
			onSuccess: (function (data) {
				for (i = 0; i < data.length; i++) {
                                        if (data[i].items.length > 0) {
                                                var elementList = new Element('p');

                                                for (j = 0; j < data[i].items.length; j++) {
                                                        elementList.adopt(
                                                                new Element('a', {
                                                                        'href': data[i].items[j].link,
                                                                        'text': data[i].items[j].title,
                                                                        'class': ((j == 0)?'firstItem':'')
                                                                })
                                                        );
                                                }
                                                
                                                this.addNode(data[i].title, elementList);
                                        }
				}
				
				// all items added - start ticker
				this.start();
			}).bind(this)
		}).get();
	}
});var Countdown = new Class({
	
	Implements: [Options,  Events],
	
	options: {
		dayField: 'days',
		hourField: 'hours',
		minuteField: 'minutes',
		secondField: 'seconds',
		useSeconds: true
	},
	
	container: null,
	
	currentDay: 0,
	
	currentHour: 0,
	
	currentMinute: 0,
	
	currentSecond: 0,
		
	initialize: function(container, options) {
		this.setOptions(options);
		this.container = $(container);
		
		// get current time values from container
		this._updateValuesFromContainer();
	},
	
	start: function() {
		if (this.options.useSeconds) {
			// call every second
			this._updateSeconds.periodical(1000, this);
		} else {
			// call every minute
			this._updateMinute.periodical(1000 * 60, this);
		}
	},
	
	_getField: function(key) {
		var field = this.container.getElement('#' + key);
		if (field) {
			return field.get('text');
		}
	},
	
	_setField: function(key, value) {
		this.container.getElement('#' + key).set('text', value);
	},
	
	_updateDay: function(currentDay) {
		--this.currentDay;
		this._setField(this.options.dayField, this.currentDay);
	},
	
	_updateHour: function(currentHour) {
		--this.currentHour;
		
		if (this.currentHour < 0) {
			this.currentHour = 24;
			this._updateDay();
		}
		
		this._setField(this.options.hourField, this.currentHour);
	},
	
	_updateMinute: function(currentMinute) {
		--this.currentMinute;
		
		if (this.currentMinute <= 0) {
			this.currentMinute = 60;
			this._updateHour();
		}
		
		this._setField(this.options.minuteField, this.currentMinute);
	},
	
	_updateSeconds: function(currentSecond) {
		--this.currentSecond;
		
		if (this.currentSecond <= 0) {
			this.currentSecond = 60;
			this._updateMinute();
		}
		
		this._setField(this.options.secondField, this.currentSecond);
	},
	
	_updateValuesFromContainer: function () {
		if (this.container) {
			this.currentDay 	= this._getField(this.options.dayField);
			this.currentHour 	= this._getField(this.options.hourField);
			this.currentMinute 	= this._getField(this.options.minuteField);
			
			if (this.options.useSeconds) {	
				this.currentSecond 	= this._getField(this.options.secondField);
			}
		}
	}
});var Toolbar = new Class({
	
	Implements: [Options,  Events],
	
	options: {
		id: 'toolbar'
	},
		
	toolbarContainer: null,
	
	visible: true,
	
	initialize: function() {
		this._setupToolbar();
	},
	
	hide: function() {
		if (this.visible) {
			this.visible = false;
			new Fx.Tween(this.toolbarContainer, {duration: 1000}).start('height', 0);
		}
	},
	
	show: function() {
		if (!this.visible) {
			this.visible = true;
			new Fx.Tween(this.toolbarContainer, {duration: 1000}).start('height', 36);
		}
	},
	
	_setupToolbar: function() {		
		this.toolbarContainer = new Element('div', {
			id: this.options.id
		});
		$(document.body).adopt(this.toolbarContainer);
		
	}
});var NewsToolbar = new Class({
	
	Extends: Toolbar,
	
	tickerTape: null,
		
	hide: function() {
		this.parent();
		
		if (this.tickerTape) {
			this.tickerTape.stop();
		}
	},
	
	show: function() {
		this.parent();
		
		if (this.tickerTape) {
			this.tickerTape.start();
		}
	},
	
	_setupToolbar: function() {
		this.parent();
				
		this.toolbarContainer.adopt(
			new Element('div', {
				id: 'toolContainer'
			}).adopt(
				new Element('a', {
					href: '/ticker/'
				}).adopt(
					new Element('img', {
						src: 'http://static.routesonline.com/images/common/routesAlerts.gif'
					})
				),

				new Element('div', {
					id: 'ticker'
				})
			)
		);
		
		
		// set up news ticker
		this.tickerTape = new AjaxTickerTape($('ticker'), {
			url: '/ajax/tickertape.php'
		});
	}
});