var TICKER_REFRESH_MILLIS = 60000;
var TICKER_DRAW_MILLIS = 5000;
var TICKER_NA_TEXT = "N/A";
var nextUpdateMillis = TICKER_REFRESH_MILLIS;
var fiveMinuteData;
var currentIndex = 0;

var drawTimeout;
var tickerTimeout;

function nextTickerLocation() {
	if(fiveMinuteData) {
		if((currentIndex) == fiveMinuteData.locations.length) {
			currentIndex = 0;
		} else {
			currentIndex++;
		}
	}
}

function drawTicker() {
    if(fiveMinuteData && fiveMinuteData.locations[currentIndex]) {
		currentLocation = fiveMinuteData.locations[currentIndex];
		
		$('lmp').innerHTML = currentLocation.lmp;
		$('tickerLocationName').innerHTML = currentLocation.locationName;
		
		$('energyComp').innerHTML = currentLocation.energyComponent;
		$('congestComp').innerHTML = currentLocation.congestionComponent;
		$('lossComp').innerHTML = currentLocation.lossComponent;
		
		if(fiveMinuteData.systemLoad) {
			$('load').innerHTML = fiveMinuteData.systemLoad;
		} else {
			$('load').innerHTML = TICKER_NA_TEXT;
		}
		$('tickerDate').innerHTML = currentLocation.date;
	}
	drawTimeout = window.setTimeout("incrementAndDraw()", TICKER_DRAW_MILLIS);
	//alert('drawTicker done');
}

function incrementAndDraw() {
	nextTickerLocation();
	drawTicker();
}

function setFiveMinuteData(data) {
    //alert('setFiveMinuteData');
	nextUpdateMillis = data.nextUpdateMillis;
	var wasNull = (fiveMinuteData == null ? true : false);
	
	fiveMinuteData = data;
	if(wasNull) {	  
		drawTicker();
	}
}

function handleError() {
	nextUpdateMillis = TICKER_REFRESH_MILLIS;
	
	if(!fiveMinuteData) {
		if(drawTimeout) {
			window.clearTimeout(drawTimeout);
		}
		
		fiveMinuteData = null;
		$('tickerLocationName').innerHTML = "Not Available";
		$('lmp').innerHTML = TICKER_NA_TEXT;
		$('tickerLocationName').innerHTML = TICKER_NA_TEXT;
		
		$('energyComp').innerHTML = TICKER_NA_TEXT;
		$('congestComp').innerHTML = TICKER_NA_TEXT;
		$('lossComp').innerHTML = TICKER_NA_TEXT;
		
		$('load').innerHTML = TICKER_NA_TEXT;
		$('tickerDate').innerHTML = TICKER_NA_TEXT;
	}
}

function updateTickerData() {
	//Element.show('loadingIndicator');
	new Ajax.Request("/LMPTicker/fiveminlmp.do",
   		{ 	method: 'GET',
   			parameters: {submit: 'json'},
   			onSuccess: function(transport, json) {
   				if(json) {
	   				var jsonObject = transport.responseText.evalJSON();
	   				setFiveMinuteData(jsonObject);
   				} else {
   					handleError();
   				}
   			},
   			onFailure: function(transport) {
   				//alert("failure");
   				handleError();
   			    
   			},
   			onException: function(transport, exception) {
   			    //alert(exception);
   			    handleError();
   			},
   			onComplete: function(transport) {
   				//Element.hide('loadingIndicator');
   				tickerTimeout = window.setTimeout("updateTickerData()", nextUpdateMillis);
   			}   			
   		});
}

function Ticker() {
	updateTickerData();
}
