// script base url
var base = 'http://www.iowa.gov/recovery';

// version info
var version = '1.5.0';

// graph data object
var graph_data = null;

// execute
$(document).ready( function() {
	
	init();
	
});

// resets everything
function init() {
	poll();
	update();
}

// after the updated chart has been created
function rendered() {
	
	resetbubble();
	wiring();
	//
	
}

// pull data from server
function poll() {

	// full size from start
	if ($('#money_distribution').height() < 200) {
		$('#money_distribution').height(266);
	}

	// use the info bubble to display loading message at the start
	var content = '<table width="100%" height="100%">';
	content += '<tr><td align="center" valign="middle"><img src="' + base + '/images/35-1.gif">';
	content += '<br/><strong>Fetching Charts</strong></td></tr></table>';
	$('#infobubble').html(content);

	// locate the data table
	var offset = $('#money_distribution').position();

	// working screen
	$('#infobubble').css('top', offset.top + 'px');
	$('#infobubble').css('left', (offset.left-12) + 'px');
	$('#infobubble').css('width',($('#money_distribution').width() - 40) + 'px');
	$('#infobubble').css('height', $('#money_distribution').height() + 'px');
	$('#infobubble').css('background', '#ffffff');
	$('#infobubble').show();
	$('#infobubble').fadeTo("fast", 0.60);
	
	// poll chart
	var service = base + '/api/recovery.html';
	$.get(service, {}, function(data) {

	        // use the info bubble to display loading messages
	        var content = '<table width="100%" height="100%">';
	        content += '<tr><td align="center" valign="middle"><img src="' + base + '/images/35-1.gif">';
	        content += '<br/><strong>Building Charts</strong></td></tr></table>';
	        $('#infobubble').html(content);
	        $('#money_distribution').html(data);
	        rendered();
		
	}, "text");
	
	// poll data
	var service = base + '/api/recovery.json';
	$.get(service, {}, function(data) {
			graph_data = data;
			piecharts();
	},'json');

}

// polls for updated data and keeps the chart current
function update() {

	// keep data up to date
	var service = base + '/api/recovery.php?version=' + version  + '&base=' + base;
	$.get(service, {}, function(data) {
		// don't display anything
		}, "json");


	// refresh every 15 minutes
	setTimeout('init();',900000);


}

// reset the bubble
function resetbubble() {

	$('#infobubble').css('width', '355px');
	$('#infobubble').css('height', '310px');
	$('#infobubble').fadeTo("slow", 1.0).hide();
	$('#infobubble').css('background', 'transparent');
	if (jQuery.browser.msie || jQuery.browser.safari) {
		$('.topshader').hide();
		$('.leftshader').hide();
		$('.bottomshader').hide();
	}
	
}

// attach events 
function wiring() {

	$('.valueAmount').formatCurrency();
	$('td.total').formatCurrency();
	
	$('.stackedbar').mouseenter(function(event) { hoversub(event); });
	$('.stackedbar').mouseleave(function(event) { unhoversub(event); });
	$('.stackedbar').mousemove(function(event)  { movesub(event);	});
		
	$('.groupbar').each( function(index) {
		var width = $(this).attr('animatewidth');
		$(this).animate( {'width' :width + "%"
	}, { queue :true, duration :1400 });
	});
	
	$('.groupview').each( function(index) {
		$(this).click( function(event) {
			opendetail(event.target);
		});
	});
	
	$('.pieicon').mouseenter(
			function(event) {

				temptitle = $(event.target).attr('title');
				$(event.target).attr('title','');
				var group = $(event.target).attr('group');
				var fund  = $(event.target).attr('fund');
				var index = $(event.target).attr('index');
				var total = $(event.target).attr('total');
				var amount   = $(event.target).attr('amount');
				var name   = $(event.target).attr('name');
				var source = $(event.target).attr('source');

				var color = '';
				if (source == 'formula') color = 'B7D427';
				if (source == 'estimate')	color = 'C77F26';
				if (source == 'demand') color = '406CAA';
				
				 var percent = Math.round((amount/total)*100);
                 var remains = (total-amount);
                 var rpercent = Math.floor((remains/total)*100);
                 if(percent<1) percent = 'less than 1';

                 // build html for bubble
                 var html = '<p><strong>' + name + ' Overview</strong></p><p>';
                 html += 'This chart shows an overview which represents the ' + formatCurrency(amount);
                 html += ' (' + percent + '%) of the ' + formatCurrency(total) + ' (' + fund + ' Total)';
                 html += ' that is dedicated to the ' + name + ', and the remaining ' + formatCurrency(remains) + '';
                 html += '  (' + rpercent + '%) which';
                 html += ' is dedicated elsewhere.</p>';
                 html += '<div id="bubblechart"></div>';


				$('#infobubble').html(html);
				subpie(total, amount, color, formatCurrency(amount),true);
				$('#infobubble').show();
				placeoverlay(event, '#infobubble');
				
			});
	
	$('.pieicon').mouseleave(
			function(event) {
				$(event.target).attr('title',temptitle);
				$('#infobubble').hide();
			});
	
	// update total text
	var total = $('td.total').text();
	total = (parseFloat(total.replace(/[^0-9\.]/g, ''))/1000000000);
	total = Math.round(total*Math.pow(10,2))/Math.pow(10,2);
	$('#amount').text('' + total + ' billion dollars ');
		
}

// zoom into detail
function opendetail(handle) {

	var target = $(handle).attr('id').replace('_zoom', '_table');
	if ($('#' + target).css('display') == 'block' || $('#' + target).css('display') == 'table-row-group') {
		$('#' + target).fadeOut('slow');
	} else {
		$('.subgrouper').hide();
		$('.subcategories').fadeOut();
		$('#' + target).fadeIn('slow');
	}
}

// gets google visualization charts
function piecharts() {
	
	var formula = 0;
	var estimate = 0;
	var demand = 0;
	
	for ( var group in graph_data) {
		estimate+=parseInt(graph_data[group]['estimate']);
		formula+=parseInt(graph_data[group]['formula']);
		demand+=parseInt(graph_data[group]['demand']);		
	}
	
	
	var chart = {};
	
	chart.type = 'p3';
	chart.size = 438 + 'x' + 160;
	chart.title = 'Funding Overview by Fund Type';
	chart.colors = ['#B7D427','#406CAA','#C77F26'];
	chart.data = Array();
	
		chart.data[0] = {};
		chart.data[0].value = formula;
		chart.data[0].label =  'Formula';
		chart.data[0].legend = undefined;
		chart.data[0].color  = 'B7D427';

                chart.data[1] = {};
                chart.data[1].value = demand;
                chart.data[1].label =  'Demand';
                chart.data[1].legend = undefined;
                chart.data[1].color  = '406CAA';
		
		chart.data[2] = {};
		chart.data[2].value = estimate;
		chart.data[2].label =  'Competitive';
		chart.data[2].legend = undefined;
		chart.data[2].color  = 'C77F26';
		
	
	$('#grouppiechart').visualization(chart);
	
	var color = [ '927B51','BCDD5A','80C31C','A89166','FF7900','FBB36B','aaaaaa','006666' ];
	
	var chart = {};
	chart.type = 'p3';
	chart.size = 438 + 'x' + 160;
	chart.title = 'Funding Overview by Major Area';
	chart.data = Array();
	
	var x = 0;
	for ( var group in graph_data) {
		
		chart.data[x] = {};
		chart.data[x].value = parseInt(graph_data[group]['amount']);
		chart.data[x].label =  group;
		x++;
		
	}
	
	$('#newtotalspiechart').visualization(chart);
}


var temptitle = '';
// hover on bar segments
function hoversub(event) {

	// clear title while we're showing the graph
	temptitle = $(event.target).attr('title');
	$(event.target).attr('title', '');
	
	// capture semi-important info
	var background = event.target.id.split('_');
	var fund_type = background[0];

	// capture fund info
	var value = $(event.target).parent('div').parent('td').attr('value');
	var type = $(event.target).parent('div').parent('td').attr('type');
	var group = $(event.target).parent('div').parent('td').attr('group');
	var fund = $(event.target).parent('div').parent('td').attr('fund');
	var amount = $(event.target).attr('amount');
	var total = $(event.target).attr('total');
	
	// pulsing background
	$('#' + event.target.id).css('background-image',
			"url('" + base + "/images/" + background[0] + "-hover.gif')");

	// place and position the bubble
	placeoverlay(event, '#infobubble');

	// pick colors
	var color = '';
	if (fund_type == 'formula') color = 'B7D427';
	if (fund_type == 'estimate')	color = 'C77F26';
	if (fund_type == 'demand') color = '406CAA';

	// render pie chart
	if(type==1) {
		
		if (fund_type == 'formula')
			var label = 'Formula-Based - Funding is allocated by an established federal formula to States and localities. Formula-Based funding ';
		if (fund_type == 'demand')
			var label = 'Demand-Based - Funding responds directly to demand from eligible individuals.  The dollar amount Iowa receives will vary according to the number of people who qualified and received the funding. These numbers may change as actual funds are distributed. Demand-Based funding ';
		if (fund_type == 'estimate')
			var label = 'Competitive - Funding is allocated through competitive solicitations federally.  Competitive funding ';
		
		// build html for bubble
		var html = '<p><strong>' + group + ' Overview</strong> - ';
		html += '' + label + ' accounts for ' + temptitle + '</p>';
		html += '<div id="bubblechart"></div>';
		
		$('#infobubble').html(html);
		$('#infobubble').show();
		
		subpie(total, amount, color, fund_type);
	}
	if(type==3) {

		var percent = Math.round((amount/total)*100);
		if(percent<1) percent = 'less than 1';

		// build html for bubble
		var html = '<p><strong>' + fund + ' Overview (' + fund_type + ')</strong></p><p>';
			html += 'This chart shows an overview which represents ' + formatCurrency(amount) + ' (' + percent + '%) of the ' + formatCurrency(total) + ' (' + group + ' Total) that is dedicated to the ' + fund + ', and the remaining portion which is dedicated elsewhere.</p>';
		html += '<div id="bubblechart"></div>';

		$('#infobubble').html(html);
		$('#infobubble').show();

		subpie(total, amount, color, formatCurrency(amount),true);
	}
	
	if(type==2) {
		
		// build html for bubble
		var html = '<p><strong>' + fund + ' Overview</strong></p><p>';
			html += 'This chart shows an overview which represents the sub-portions of the ' + formatCurrency(total) + ' (' + group + ' Total) that are dedicated to the ' + fund + '.</p>';
		html += '<div id="bubblechart"></div>';

		$('#infobubble').html(html);
		$('#infobubble').show();

		fundpie(group,fund);
	}
}

// position popup bubble
function placeoverlay(event, selector) {

	var obj = {
		'height' :$(selector).outerHeight(),
		'width' :$(selector).outerWidth()
	};
	var overflow = {
		'top' :$(window).scrollTop(),
		'bottom' :($(window).height() + $(window).scrollTop()),
		'left' :$(window).scrollLeft(),
		'right' :($(window).scrollLeft() + $(window).width())
	};
	var def = {
		'top' :event.pageY,
		'left' :event.pageX
	};
	var dangle = 40;
	var buffer = 2;

	// graphic and position decision
	var bubble = selector.replace(/[^A-z]/g, '');
	if ((def.top + obj.height + buffer) > overflow.bottom) {
		if ((def.top - (obj.height + buffer)) < overflow.top) {
			if ((def.left + obj.width + buffer) > overflow.right) {
				// left pos
				bubble += 'left';
				var pos = {
					'top' :(def.top - ((obj.height / 2) - (dangle / 2))),
					'left' :(def.left - (obj.width + (buffer)))
				};
			} else {
				// right pos
				bubble += 'right';
				var pos = {
					'top' :(def.top - ((obj.height / 2) - (dangle / 2))),
					'left' :(def.left + buffer)
				};
			}
		} else {
			// top pos
			bubble += 'top';
			var pos = {
				'top' :(def.top - (obj.height + buffer)),
				'left' :(def.left - (dangle))
			};
		}
	} else {
		
		if ((def.left + obj.width + buffer) > overflow.right) {
			// bottom left
			bubble += 'bottomleft';
			var pos = {
				'top' :(def.top + buffer),
				'left' :(def.left - ((obj.width-dangle) + (buffer)))
			};
		} else {
			// bottom right
			bubble += 'bottom';
			var pos = {
				'top' :(def.top + buffer),
				'left' :(def.left - (dangle))
			};
		}
	}

	// choose alpha or plain
	if (jQuery.browser.msie) {
		bubble += '.gif';
	} else {
		bubble += '.png';
	}

	$(selector).css('background-image',
			"url('" + base + "/images/" + bubble + "')");
	$('#infobubble').css('top', pos.top + 'px');
	$('#infobubble').css('left', pos.left + 'px');

}

// position overlay
function movesub(event) {
	placeoverlay(event, '#infobubble');
}

// hide overlay
function unhoversub(event) {

	$(event.target).attr('title', temptitle);
	var background = event.target.id.split('_');
	$('#' + event.target.id).css('background-image',
			"url('" + base + "/images/" + background[0] + ".gif')");
	$('#infobubble').hide();
}

// generates the pie charts for the bubbles
function subpie(total, amount, color, label, label2) {

	total = makeInt(total);
	amount = makeInt(amount);
	var difference = (total - amount);
	
	var chart = {};
	chart.type = 'p3';
	chart.size = '370x140';
	chart.data = Array();
	chart.legend_position = 'bv';
	
	chart.data[0] = {};
	chart.data[0].value = amount;
	chart.data[0].label =  label.charAt(0).toUpperCase() + label.substr(1);
	chart.data[0].color = color;
	
	if(difference>0) {
		chart.data[1] = {};
		chart.data[1].value = difference;
		if(label2) {
			chart.data[1].label =  formatCurrency(difference);
		} else {
			chart.data[1].label =  'Other';
		}
		chart.data[1].color = '888888';
	}
	
		
	$('#bubblechart').chart(chart);
	
}

// placeholder
function makeInt(what) {
	return (what * 1);
}

// used to format currency for display
( function($) {

	$.fn.formatCurrency = function(settings) {
		settings = jQuery.extend( {
			name :"formatCurrency",
			useHtml :true,
			global :true
		}, settings);

		return this.each( function() {
			var num = "0";
			num = $(this)[settings.useHtml ? 'html' : 'val']();
			num = num.replace(/\$|\,/g, '');
			if (isNaN(num))
				num = "0";
			sign = (num == (num = Math.abs(num)));
			num = Math.floor(num * 100 + 0.50000000001);
			cents = num % 100;
			num = Math.floor(num / 100).toString();
			if (cents < 10)
				cents = "0" + cents;
			for ( var i = 0; i < Math.floor((num.length - (1 + i)) / 3); i++)
				num = num.substring(0, num.length - (4 * i + 3)) + ','
						+ num.substring(num.length - (4 * i + 3));

			$(this)[settings.useHtml ? 'html' : 'val'](((sign) ? '' : '-')
					+ '$' + num + '.' + cents);
		});
	};

})(jQuery);

function formatCurrency(num) {
	if (isNaN(num))
		num = "0";
	sign = (num == (num = Math.abs(num)));
	num = Math.floor(num * 100 + 0.50000000001);
	cents = num % 100;
	num = Math.floor(num / 100).toString();
	if (cents < 10)
		cents = "0" + cents;
	for ( var i = 0; i < Math.floor((num.length - (1 + i)) / 3); i++)
		num = num.substring(0, num.length - (4 * i + 3)) + ','
				+ num.substring(num.length - (4 * i + 3));

	return '$' + num;
}


