$(document).ready(function(){

	// get a list of stock symbols to look up from the markup
	syms = '';
	$('table.market th').each(function(i) {
		$self = $(this);
        if ($self.attr('title')) {
			syms += $self.attr('title').replace("=","%3D","g")+',';
			
			var trColor = $self.parent().css('backgroundColor');
			$self.parent().hover(
				function(){
					$(this).css({
						backgroundColor: '#414042',
						cursor: 'pointer'
					});
				},
				function(){
					$(this).css({
						backgroundColor: trColor
					});
				}
			);
	
			$self.parent().click(function() {
				//alert($(this).parent().parent().next().attr('id'));
				drawGraph('#'+$(this).parent().parent().next().next().attr('id'),$(this).find('th').attr('title'));
			});

		}
    });
 	// remove trailing comma
	syms = syms.slice(0, -1);
	// encode = characters
	//syms = syms.replace("=","%3D","g");
	
	// grab stock quotes from Yahoo Finance using YQL
	var yql	=	"select symbol, price, change, percent "+
				"from csv "+
				"where url='http://download.finance.yahoo.com/d/quotes.csv?s="+syms+"&f=sl1d1t1c1ohgvp2&e=.csv' "+
				"and columns='symbol,price,date,time,change,col1,high,low,col2,percent'";				
	
	var yqlUrl = 'http://query.yahooapis.com/v1/public/yql?q='+yqlEscape(yql)+'&format=json&callback=?';
	
	//alert(yqlUrl);
	
	$.getJSON(yqlUrl, {type: 'json'}, function(data){
		if (data.query !== null) {
			if (data.query.results !== null) {		
		 		 $.each(data.query.results.row, function(index, item){
					var percent='';
					var change = '';
					var price= item.price;
		
					if (item.change != 'N/A') {
						change = item.change;
						if (change <0) {
							change = '<span>'+percent+'</span>';
						}
					}

					if (item.percent != '"N/A"') {
						percent = item.percent.slice(0, -2).substr(1);
						if (percent <0) {
							percent = '<span>'+percent+'</span>';
						}
					} 
					//add to table row
					$('[title='+item.symbol+']').next().html(price).next().html(change).next().html(percent);
				 });
			}
		}
	});

	// draw graphs	
	$('.graph').each(function(i) {
		drawGraph('#'+$(this).attr('id'),$(this).prev().text());
	});
	

});	

function yqlEscape(r) {
	// does normal encodeURIComponent and then takes care of !, *, ', (, and )
	return encodeURIComponent(r).replace("!","%21","g").replace("*","%2C","g").replace("(","%28","g").replace(")","%29","g");
}	
	
function drawGraph(obj,sym) {
		
	var yesterday = new Date();
	yesterday.setDate(yesterday.getDate()-1);

	var datePast = new Date();
	datePast.setDate(datePast.getDate()-15);

	// grab historical data	
	/*
	Yahoo finance query parameters
	s = stock symbol
	a = start month
	b = start day
	c = start year
	d = end month
	e = end day
	f = end year
	ignore = file extension required
	*/
	var yql	="select Date,Open,High,Low,Close,Volume,Adj_Close "+
			"from csv "+
			"where url='http://ichart.finance.yahoo.com/table.csv?s="+sym+"&a="+datePast.getMonth()+"&b="+datePast.getDate()+"&c="+datePast.getFullYear()+"&d="+yesterday.getMonth()+"&e="+yesterday.getDate()+"&f="+yesterday.getFullYear()+"&ignore=.csv' "+
			"and columns='Date,Open,High,Low,Close,Volume,Adj Close' "+
			"limit 9";	
		
	var yqlUrl = 'http://query.yahooapis.com/v1/public/yql?q='+yqlEscape(yql)+'&format=json&callback=?';

	$.getJSON(yqlUrl, function(data){
		if (data.query !== null) {
			if (data.query.results !== null && data.query.results.row.length==9) {
	  			var closeValues = new Array;
				  var dtStart ='';
				  var dtEnd ='';
				  $.each(data.query.results.row, function(index, item){
						if (index>0 &&index<9) { // limit to 8 items
							closeValues.push(item.Close);
						}
						if (index == 1) {
							dtEnd = item.Date;
						} else if(index==8) {
							dtStart = item.Date;
						}
				    });

					//reverse the array so the oldest dates are first
					closeValues.reverse();

					// get yesterday
					var dayNames = new Array("sun","mon","tue","wed", "thu","fri","sat");
		
					// change graph class so background image shows the last 7 works days
					$(obj).attr("class","graph "+dayNames[yesterday.getDay()]);

					// draw graph
					$(obj).show();
					$(obj).sparkline(closeValues,
						{
							width: 252,
							height: 110,
							fillColor: '',
							lineColor: '#F37B32',
							minSpotColor: 'red',
							maxSpotColor: 'green',
							spotRadius: 0
						}
					);
					
					// update graph title
					$(obj).prev('h4').html('<strong>'+sym+'</strong>' + ' '+dtStart +' &ndash; '+dtEnd);
				}
				else {
					$(obj).prev('h4').html('<strong>'+sym+'</strong> - sorry, no data for this symbol');
					$(obj).hide();
				}
			} 	
	});

}
	
