var DATAINTERVAL = 70;
var SCROLLINTERVAL = 10;
var BREAKINGINTERVAL = 180;
var AJAXREQUEST = "/ajax?op=newsticker"
var tijdNewsticker;
var textRecent;
var textBreaking;
var textStocks;

var newsticker = Class.create( {
	
	initialize : function( ntContainer, textRecent, textBreaking, textStocks ) {
		this.ntContainer = ntContainer;
		this.addArrowEvents();
		this.addHoverEvents();
		this.jsonData = '';
		this.initScrollPE();
		this.initDataPE();
		this.initBreakingPE();
		this.hasNewData = false;
		this.getNewData();
        this.textRecent = textRecent;
        this.textBreaking = textBreaking;
		this.textStocks = textStocks;
		this.transitionLocked = false;
	},
	
	initScrollPE : function() {
		var t = this;
		this.scrollPE = new PeriodicalExecuter( function( pe ) {
			t.showNext( true );
		}, SCROLLINTERVAL );
	},
	
	initDataPE : function() {
		var t = this;
		this.needNewData = false;
		this.dataPE = new PeriodicalExecuter( function( pe ) {
			t.setNeedNewData();
		}, DATAINTERVAL );
	},
	
	initBreakingPE : function() {
		var t = this;
		this.refreshBreaking = false;
		this.breakingPE = new PeriodicalExecuter( function( pe ) {
			t.setRefreshBreaking();
		}, BREAKINGINTERVAL);
	},
	
	showNext : function( isAutomatic ) {
		if ( isAutomatic == null || isAutomatic == undefined ) {
			isAutomatic = false;
		}
		var t = this;
		var curEl = $( this.ntContainer ).select ( '.recentnews li.current' )[0];
		if (curEl != undefined) {
			var nextEl = curEl.next();
			if (nextEl == undefined) {
				nextEl = $( this.ntContainer ).select ( '.recentnews li:first-child' )[0];
			}
			var isUpdated = false;
			
			if ( isAutomatic ) {
				if ( !$(curEl).hasClassName("breaking") || this.refreshBreaking ) {
					var doFullTransition = false;
					if ( $(curEl).hasClassName('recent') ) {
						var scrollItems = $( this.ntContainer ).select( '.current .recentArticlesScroller > a');
						var curLeft = scrollItems[0].getStyle("left");
						var newLeft = this.determineLeft( scrollItems, false );
						if (newLeft == false) {
							var doFullTransition = true;
						} else {
							if ( !t.transitionLocked ) {
								scrollItems.each( function( el ) {
									
									t.transitionLocked = true;
									new Effect.Move( el , {
										x: (-1 * newLeft), y: 0, mode: 'relative',
										transition: Effect.Transitions.sinoidal,
										afterFinish : function( effect ) { t.unlockTransition(); }
									});
								});
							}
						}
					} else {
						doFullTransition = true;
					}
						
					if ( doFullTransition ) {
						Effect.Appear( $(nextEl), {duration:1} );
						Effect.Fade( $(curEl), {duration:1} );
						if ( $(nextEl).hasClassName("breaking") ) {
							this.initBreakingPE();
						}
						isUpdated = true;
						
					}
					
				}
				if ( $(curEl).hasClassName("breaking") && $(nextEl).hasClassName("breaking") ) {
					Effect.Appear( $(nextEl), {duration:0} );
					Effect.Fade( $(curEl), {duration:0} );
					this.initBreakingPE();
					isUpdated = true;
				}
			} else {
				if ( $(curEl).hasClassName('recent') ) {
				
					var scrollItems = $( this.ntContainer ).select( '.recentArticlesScroller > a');
					curLeft = parseInt(scrollItems[0].getStyle("left").gsub('px',''));
					newLeft = this.determineLeft( scrollItems, false );
					if (newLeft == false) {
						var doFullTransition = true;
					} else {
						if ( !t.transitionLocked ) {
							t.transitionLocked = true;
							scrollItems.each( function( el ) {
								new Effect.Move( el , {
									x: (-1 * newLeft), y: 0, mode: 'relative',
									transition: Effect.Transitions.sinoidal,
									afterFinish : function( effect ) { t.unlockTransition(); }
								});
							});
						}
					}
				} else {
					doFullTransition = true;
				}
					
				if ( doFullTransition ) {
					Effect.Appear( $(nextEl), {duration:0} );
					Effect.Fade( $(curEl), {duration:0} );
					isUpdated = true;
				}
				this.hasNewData = false;
			}
			
			if ( doFullTransition ) {
				$( this.ntContainer ).select( '.current .recentArticlesScroller > a').each( function (el) {
					el.setStyle( { 'left' : '0px' } );
				});
			}
			
			if (isUpdated) {
				curEl.removeClassName("current");
				nextEl.addClassName("current");
			}
			
			if ( this.needNewData && isAutomatic && !nextEl.hasClassName('recent')) {
				this.scrollPE.stop();
				this.getNewData();
			}
			
			if ( this.hasNewData && isUpdated && isAutomatic ) {
				$(curEl).remove();
				this.hasNewData = false;
				this.isUpdated = false;
			}
			
		}
	},
	
	determineLeft : function( scrollItems, reverse ) {
		if (!reverse) {
		
			var curLeft = parseInt(scrollItems[0].getStyle('left').gsub('px',''));
			var widthToMove = 0;
			var maxWidthToMove = 0;
			scrollItems.each( function( el ) {
				maxWidthToMove += ( el.getWidth() );
			});
			
			var retLeft = false;
			scrollItems.each( function( el ) {
				
				// -1 because the "left" is a negative value
				if ( widthToMove <= ( curLeft * -1 ) ) {
					widthToMove += ( el.getWidth() );
					retLeft = ( el.getWidth() + 10 );
				}
				if ( widthToMove >= ( maxWidthToMove -100 ) ) {
					retLeft = false;
				}
				
			});
			
			return retLeft;
			
		} else {
			
			var curLeft = parseInt(scrollItems[0].getStyle('left').gsub('px',''));
			var widthToMove = 0;
			
			var retLeft = false;
			var sI = scrollItems;
			
			scrollItems.each( function( el ) {
				
				// -1 because the "left" is a negative value
				if ( widthToMove <= ( curLeft * -1 ) ) {
					widthToMove += ( el.getWidth() );
					if ( el.previousSiblings()[0] != undefined ) { 
						retLeft = ( el.previousSiblings()[0].getWidth() + 10 );
					}
				}
				
			});
			
			return retLeft;
		}
	
	},
	
	showPrev : function() {
		var curEl = $( this.ntContainer ).select ( '.recentnews li.current' )[0];
		var t = this;
		if (curEl != undefined) {
			var prevEl = curEl.previous();
			if (prevEl == undefined) {
				prevEl = $( this.ntContainer ).select ( '.recentnews li:last-child' )[0];
			}
			if ( $(curEl).hasClassName('recent') ) {
				
				var scrollItems = $( this.ntContainer ).select( '.recentArticlesScroller > a');
				curLeft = parseInt(scrollItems[0].getStyle("left").gsub('px',''));
				newLeft = this.determineLeft( scrollItems, true );
				var doFullTransition = false;
				if ( newLeft == false ) {
					doFullTransition = true;
				}
				if ( !t.transitionLocked ) {
					if ( doFullTransition ) {
					
						Effect.Appear( $(prevEl), {duration:0} );
						Effect.Fade( $(curEl), {duration:0} );
						curEl.removeClassName("current");
						prevEl.addClassName("current");
					
					} else {
					
						scrollItems.each( function( el ) {
							t.transitionLocked = true;
							new Effect.Move( el , {
								x: newLeft, y: 0, mode: 'relative',
								transition: Effect.Transitions.sinoidal,
								afterFinish : function( effect ) { t.unlockTransition(); }
							});
						});
					}
				}
			} else {
				Effect.Appear( $(prevEl), {duration:0} );
				Effect.Fade( $(curEl), {duration:0} );
				curEl.removeClassName("current");
				prevEl.addClassName("current");
			}
		}	
	},
	
	getNewData : function() {
		this.ntDst = new DST( AJAXREQUEST + "&reqtype=simple&datetime=" + new Date().getTime() );
		this.ntDst.prepare();
		this.ntDst.execute();
	},
	
	updateData : function( jsonData ) {
		this.jsonData = jsonData;
		jsonObj = this.jsonData;
		ulItem = $(this.ntContainer).select( '.recentnews ul')[0];
		
		this.scrollPE.stop();
		
		// remove all non-current items (only when NOT in recent news scroll list)
		$(ulItem).select( 'li' ).each( function( oldListItem ) {
			if (!oldListItem.hasClassName('current')) {
				oldListItem.remove();
			}
		});
		
		if ( this.hasBreakingItem( jsonObj ) ) {
			$(ulItem).insert( this.createBreakingItem( jsonObj ) );
		}
		
		$(ulItem).insert( this.createRecentItem( jsonObj ) );
		$(ulItem).insert( this.createTickerItem( jsonObj ) );
		
		this.hasNewData = false;
		this.needNewData = false;
		this.ntDst.cleanup();
		
		if ( $( this.ntContainer ).select ( '.recentnews li.current' )[0] == undefined) {
			$( this.ntContainer ).select ( '.recentnews li' )[0].addClassName("current");
		}
		if ( $( this.ntContainer ).select ( '.recentnews li.current' )[0].hasClassName('loading') ) {
			this.showNext();
			$( this.ntContainer ).select ( '.recentnews li.loading' )[0].remove();
		} else {
			this.hasNewData = true;
		}
		
		// subscribe realtime stocks
		if ( objSRF != null ) {
			new newstickerStocks().subscribe();
		}
		this.initScrollPE();
		
	},
	
	createRecentItem : function ( artObj ) {
		var tmpItem = new Element('li');
		tmpItem.addClassName('clearfix');
		tmpItem.addClassName('recent');
		tmpItem.insert('<span class="label">' + this.textRecent + '</span>');
		this.addRecentItemList( tmpItem, artObj );
		return tmpItem;
	},
	
	addRecentItemList : function ( item, artObj ) {
		var t = this;
		var strInsert = '';
		artObj.each( function ( obj ) {
			
			if ( !obj.breaking && obj.title != "") {
				if ( !obj.isEmpty ) {
					strInsert += '<a href="' + obj.url + '" class="article">' + obj.title + t.getTickerString( obj ) + '</a>';
				} else {
					strInsert += '<span class="article">' + obj.title + '</span>';
				}
			}
		});
		item.insert( '<span class="recentArticlesScroller">' + strInsert + '</span>' );
	},
	
	addBreakingItem : function( item, artObj ) {
		var t = this;
		artObj.each( function ( obj ) {
			if ( obj.breaking ) {
				if ( !obj.isEmpty ) {
					item.insert( '<a href="' + obj.url + '" class="article">' + obj.title + t.getTickerString( obj ) + '</a>' );
				} else {
					item.insert( '<span class="article">' + obj.title + '</span>' );
				}
			}
		});
	},
	
	createTickerItem : function( artObj ) {
		var t = this;
		var tmpItem = new Element('li');
		tmpItem.addClassName('clearfix');
		tmpItem.addClassName('tickers');
		tmpItem.insert('<span class="label">' + this.textStocks + '</span>');
		artObj.each( function ( obj ) {
			if ( obj.title == "" ) {
				tmpItem.insert('<span class="article tickersOnly">' + t.getTickerString( obj ) + '</span>');
			}
		});
		return tmpItem;
	},
	
	createBreakingItem : function ( artObj ) {
		var tmpItem = new Element('li');
		tmpItem.addClassName('clearfix');
		tmpItem.addClassName('breaking');
		tmpItem.insert('<span class="label">' + this.textBreaking + '</span>');
		this.addBreakingItem( tmpItem, artObj );
		return tmpItem;
	},
	
	getTickerString : function ( artObj ) {
		var tickerString = '';
		artObj.tickers.each( function( ticker ) {
			var tickerClass = ticker.value > 0 ? ' pos' : ticker.value < 0 ? ' neg' : ' equ';
			var realtimeString = ticker.isRealtime ? ' realtime' : '';
			if ( artObj.title == "" ) {
				// filthy hack for ticker row
				tickerString += '<a href="' + beursByIdPrefix + ticker.id + '" class="ticker newsticker_quote_' + ticker.id + realtimeString + tickerClass + '">' + ticker.name + ': <span>' + formatNumber(ticker.value, 2) + '%</span></a>';
			} else {
				tickerString += '<span class="ticker newsticker_quote_' + ticker.id + realtimeString + tickerClass + '">' + ticker.name + ': <span>' + formatNumber(ticker.value, 2) + '%</span></span>';
			}
		});
		return tickerString;
	},
	
	hasBreakingItem : function ( artObj ) {
		var hasBreaking = false;
		artObj.each( function ( obj ) {
			if ( obj.breaking ) {
				hasBreaking = true;
			}
		});
		return hasBreaking;
	},
	
	lockScrollTimer : function() {
		this.scrollLocked = true;
	},
	
	unlockScrollTimer : function() {
		this.scrollLocked = false;
	},
	
	unlockTransition : function() {
		this.transitionLocked = false;
	},
	addHoverEvents : function() {
		var t = this;
		$( this.ntContainer ).observe('mouseover', function( e ) {
			t.scrollPE.stop();
		});
		$( this.ntContainer ).observe('mouseout', function( e ) {
			t.initScrollPE();
		});
	},
	
	addArrowEvents : function() {
		var t = this;
		var recentButtons = $(this.ntContainer).select( '.recentbuttons a' );
		recentButtons.each( function ( but ) {
			but.observe( 'click', function( e ) {
				if ( but.hasClassName( 'back' )) {
					t.showPrev();
				} else {
					t.showNext();
				}
				e.stop();
			});
		});
	},
	
	setNeedNewData : function() {
		this.needNewData = true;
	},
	
	setRefreshBreaking : function() {
		this.refreshBreaking = true;
		this.breakingPE.stop();
	}

});

function initNewsticker( ntId, textRecent, textBreaking, textStocks ) {
	tijdNewsticker = new newsticker( $(ntId), textRecent, textBreaking, textStocks);
}

function _updateTickerData( jsonData ) {
	tijdNewsticker.updateData( jsonData );
}