// JavaScript Document

// holds variables to pass to the server to retrieve data
var datasets = Array();

$(document).ready(function(){
	
	//setup the click events for the panels.
	$('a.expander').click(function(e){
		e.preventDefault();
		panel = $(this).attr('rel');
		$('#'+panel+'On').show();
		$('#'+panel+'Off').hide();
		getData(panel);
	});
	$('a.collapser').click(function(e){
		e.preventDefault();
		panel = $(this).attr('rel');
		$('#'+panel+'On').hide();
		$('#'+panel+'Off').show();
		removeData(panel);
	});
	
	innit();
	
	// version2 stuff
	
						   
	$("ul#sharesticker").liScroll();
	
	//dd events only on certain elements inside the href.
	$('a.ddclick').click(function(e)
	{
		e.preventDefault();
		this.blur();
	});
	//dd events only on certain elements inside the href.
	$('a.ddclick span').click(function(e)
	{
		e.preventDefault();
		this.blur();
		dd = $('#'+$(this).parent().attr('rel'));
		dd.toggleClass('ddactive');
	});
	$('a.ddclick img.flag').click(function(e)
	{
		e.preventDefault();
		this.blur();
		dd = $('#'+$(this).parent().attr('rel'));
		dd.toggleClass('ddactive');
	});
	// expand/collapse all panels
	$('#expandall').click(function(e)
	{
		e.preventDefault();
		this.blur();
		dd = $('div#exchanges div.dd');
		txt = $(this).html();
		if(txt == 'expand all')
		{
			dd.addClass('ddactive');
			$(this).html('collapse all');
		}
		else
		{
			dd.removeClass('ddactive');
			$(this).html('expand all');
		}
	});
});


function innit()
{
	//TOD parse cookie for open panel information and put into datasets array variable.
	if($('#summaryOn').length)
	{
		// turn on the summary panel and get its data if its there
		$('#summaryOn').show();
		$('#summaryOff').hide();
		// just check that we don't have the dataset in the datasets array already
		index = datasets.inArray('summary',false);
		if(index === false) // must use === as this prototype method could return an index of zero, which we can't confuse with false
		{
			datasets[datasets.length]='summary';
		}		
	}
	if($('#spotPriceTable').length)
	{
		// get the spotprice data if its there
		index = datasets.inArray('spotprice',false);
		if(index === false) 
		{
			datasets[datasets.length]='spotprice';
		}
	}
	if($('#totalsDataTable').length)
	{
		// turn on the summary if its there
		index = datasets.inArray('totals',false);
		if(index === false) 
		{
			datasets[datasets.length]='totals';
		}
	}
	updateCookie(); // remembers what we have open/selected
	updateData();
}

function getData(dataset)
{
	geturl = "/ajax/home/"+dataset+"/";
	importData(geturl);	
	index = datasets.inArray(dataset,false);
	if(index === false)
	{
		datasets[datasets.length]=dataset;
	}
	updateCookie();
}

function removeData(dataset)
{
	index = datasets.inArray(dataset,false);
	if(index !== false)
	{
		//remove the dataset from the datasets array... the panel should be closed and we shouldn't retrieve it anymore.
		//alert('in array with index '+index);
		datasets.splice(index,1);
		//alert('not anymore '+ datasets.join(','));
	}
	updateCookie();
}

function updateData()
{
	if(datasets.length > 0)
	{
		geturl = "/ajax/home/"+datasets.join(',')+"/";
		importData(geturl);
	
	}
	setTimeout(updateData,60000); // do it all again in one minute.
}

function importData(geturl)
{
	// pass the interval param zero, forcing the FS_ajaxFeed to kill itself when done.
	page_ajax = new FS_ajaxFeed(['columnCenter','spotPriceTable','totalsDataTable'],geturl,0);
	page_ajax.loadAjaxData();
	
}

function updateCookie()
{
	createCookie('etgpanels',datasets.join(','),7,'/'); 
}

function createCookie(name,value,days,path) 
{
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path="+path;
}

function readCookie(name) 
{
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) 
{
	createCookie(name,"",-1);
}


//trims whitespace from a string
function trim(str)
{
	return str.replace(/^\s+|\s+$/g, '');	
}

// extends the JS Array object
// Returns index of the element if the passed value is found in the
// array. Returns false if it is not.
Array.prototype.inArray = function (value,caseInSensitive)
{
	var i;
	for (i=0; i < this.length; i++) 
	{
		if(caseInSensitive)
		{ //perform a match even the string is case sensitive
			if (this[i].toLowerCase() === value.toLowerCase()) 
			{
				return i;
			}
		}
		else
		{
			if (this[i] === value)
			{
				return i;
			}
		}
	}
	return false;
};

// news ticker scroller.
jQuery.fn.liScroll = function(settings) {
		settings = jQuery.extend({
		travelocity: 0.07
		}, settings);		
		return this.each(function(){
				var $strip = jQuery(this);
				$strip.addClass("newsticker");
				var stripWidth = 1;
				var $mask = $strip.wrap("<div class='mask'></div>");
				var $tickercontainer = $strip.parent().wrap("<div class='tickercontainer'></div>");								
				var containerWidth = $strip.parent().parent().width();	//a.k.a. 'mask' width 	
				$strip.find("li").each(function(i){
				stripWidth += jQuery(this, i).width();
				});
				$strip.width(stripWidth);			
				var defTiming = stripWidth/settings.travelocity;
				var totalTravel = stripWidth+containerWidth;								
				function scrollnews(spazio, tempo){
				$strip.animate({left: '-='+ spazio}, tempo, "linear", function(){$strip.css("left", containerWidth); scrollnews(totalTravel, defTiming);});
				}
				scrollnews(totalTravel, defTiming);				
				$strip.hover(function(){
				jQuery(this).stop();
				},
				function()
				{
					var offset = jQuery(this).offset();
					var residualSpace = offset.left + stripWidth;
					var residualTime = residualSpace/settings.travelocity;
					scrollnews(residualSpace, residualTime);
				});			
		});	
};

