var currentUpdate=0, length=0, currentChar=0, start=0, t=0;
var timeStep=50, timeStepBack=2, timeInterval=1000;
var width=70;

var tickerStuff=new Array();

function getTickerData() {
	$.ajax({
		type:"POST",
		url:"http://www.shaastra.org/2010/main/tickerArray.php",
		data:"gettickerStuff=true",
		success:function(response) {
			tickerStuff = eval(response);
			displayUpdatesInPanel();
			type();
		}
	});
}
function displayUpdatesInPanel() {
	$('#header-updates-text').html("");
	$('#header-updates-text').append("<ul></ul>");
	for (var i=0; i<tickerStuff.length; i++) {
		if (tickerStuff[i]['active']=='1') { 
			$('#header-updates-text ul').append("<li><a href=\"" + tickerStuff[i]['updateLink'] + "\">"+tickerStuff[i]['updateText']+"</a></li>");
		}
	}
	

}

$(document).ready(function () {
	
	
	$('#ticker-img-right').click(function() {
		clearTimeout(t);		
		untypeNext()
	});
	$('#ticker-img-left').click(function() { 
		clearTimeout(t);
		untypePrev()
	});
	getTickerData();

	$('#header-updates-text').slideUp();
	$('#header-updates-button a').toggle(function() {
		$('#header-updates-text').stop(true,true).slideDown('slow'); 
		$(this).html("Close"); return false
	}, function() {
		$('#header-updates-text').stop(true,true).slideUp('slow');
		$(this).html("Updates");
		return false
	});
});



function display(str) {
	length = currentChar-start+1;
	if (length>width) {
		$('#ticker-link-text').html(str.substr(length-width+1, currentChar));
	}
	else {
		$('#ticker-link-text').html(str);
	}
}

function type() {

	if (currentChar>=tickerStuff[currentUpdate]['updateText'].length) { 
		clearTimeout(t);
		t=setInterval("untypeNext()", timeInterval);
	}

	else{
		display(tickerStuff[currentUpdate]['updateText'].substr(0, ++currentChar));
		$('#ticker-link-text').attr("href",tickerStuff[currentUpdate]['updateLink']);
		t=setTimeout("type()", timeStep); 
	}
};

function untypeNext() {
	display(tickerStuff[currentUpdate]['updateText'].substr(0, --currentChar));
	if (currentChar!=0) {
		clearTimeout(t);
		t=setTimeout("untypeNext()", timeStepBack); }
	else {
		if (currentUpdate>=tickerStuff.length-1) {currentUpdate=-1;} currentUpdate++;
		type(); 
	}
	
};
function untypePrev() {
	display(tickerStuff[currentUpdate]['updateText'].substr(0, --currentChar));
	if (currentChar!=0) {
		clearTimeout(t); t=setTimeout("untypePrev()", timeStepBack);  }
	else {
		if (currentUpdate<=0) {currentUpdate=tickerStuff.length;} currentUpdate--;
		type(); 
	}
};
