
function htmlDecode(value){ 
  return $('<div/>').html(value).text(); 
}


$(document).ready(function(){

// homepage slideshow	
	$('.slideshow li a:first').closest('li').addClass('on');
	$('.slides div:first').addClass('on');
	$('.slideshow .accent_image:first').addClass('on');

	$('.slideshow a').click(function(){
		var activeClass = $(this).attr('class');
		$('.slideshow li').removeClass('on');
		$(this).closest('li').addClass('on');
		
		if($('.slides div.' + activeClass).is(':visible')==false) {
			$('.slides div:visible').fadeOut(150);
			$('div.accent_image:visible').fadeOut(150);
			$('.slides div.' + activeClass).fadeIn(150);
			$('div.accent_image.' + activeClass).fadeIn(150);
		}
		
		return false;
	});

// zebra stripe	
	$('.stripe tbody tr:odd, .history tbody tr:odd').addClass('alt');
	$('ul.docList li:even').addClass('alt');
	
	
// table rule fix
	$('table.strategies tr').each(function(){
		$(this).find('td:last').removeClass('ruled');
	});	
	
	

// strategy selector expand / contract
	$('.strategy-select a.strat-expand').click(function(){
		if($(this).hasClass('on')) {
			$('.strategy-select li').not($(this).parent()).slideUp(200);
			$(this).removeClass('on');
		} else {
			$(this).addClass('on');
			$('.strategy-select li:hidden').slideDown(200);
		}

		return false;
	});	



// create all pie charts
	$('.piechart').each(function(){
	
		var data = [];
		var piecolors = [];
		var id = $(this).find('.pie_container').attr('id');
			
		$(this).find('.pie_slice').each(function(){
			piecolors[piecolors.length] = $(this).attr('data-color');
			data.push([$(this).find('.pie_key').html() , parseFloat($(this).find('.pie_value').attr('value'))]);
		})
		
			
		var piesettings = {
			chart: {
				renderTo: id,
				margin: [0, 60, 0, 0],
				width: 190
			},
			tooltip: {
				formatter: function() {
					return '<b>'+ htmlDecode(this.point.name) + ':</b>'+ this.y.toFixed(1) +'%';
				},
				style: {
					width: '150px',
					fontWeight: 'bold'
				}
			},
			series: [{
				type: 'pie',
				data: data
			}],
			colors: piecolors
		};
		
		//piesettings.colors = piecolors;

			
		new Highcharts.Chart(piesettings);
	});
	

// create all line charts
	$('.linechart').each(function(){
	
		var series = [];
		var colors = [];
		var id = $(this).attr('id');
		ylabel = $(this).find('.y_label').html();
		
		$(this).find('div.series').each(function(){
			data = [];
			name = $(this).attr('name');
			
			colors.push($(this).attr('color'));
			
			$(this).find('div').each(function(){
				date = new Date($(this).attr('date'));
				year = date.getFullYear();
				if(year<1920) {
					year = year + 100;
				}
				data.push([Date.UTC(year,date.getMonth(),date.getDate()) , parseFloat($(this).attr('value'))]);
			})
			series.push({type:'line',data:data,name:name});
		})

		var linechart;
		linechart = new Highcharts.Chart({
			chart: {
				renderTo: id,
				margin: [10, 0,80,80]
				//,
			//	type: 'spline'
			},
			plotOptions: {
				series: {
					marker: {
						enabled:false
					}
				}
			},
			xAxis: {
				type:'datetime',
				labels: {
					formatter: function() {
						return Highcharts.dateFormat("%b '%y", this.value);
					}
				},
				maxPadding: .07
			},
			series: series,
			colors: colors,
			yAxis: {
				title: {
            		text: ylabel,
            		style: {
						color: '#000000',
						fontWeight: 'normal'
					}
				},
				labels: {
					formatter: function() {
						return '$' + addCommas(this.value);
					}
				}
        	},
        	tooltip: {
        		formatter: function() {
            		return '<b>' + this.series.name + '</b><br/>' + Highcharts.dateFormat("%B %e, %Y", this.x) + ': $' + addCommas(this.y);
        		}
        	}
		});
	});


// create all bar charts
	$('.barchart').each(function(){
	
		series = [];
		colors = [];
		var id = $(this).attr('id');
		ylabel = $(this).find('.y_label').html();
		
		$(this).find('div.series').each(function(){
			data = [];
			categories = [];
			name = $(this).attr('name');
			
			colors.push($(this).attr('color'));
			
			$(this).find('div').each(function(){
				date = $(this).attr('date');
				data.push([date , parseFloat($(this).attr('value'))]);
				categories.push(date);
			})
			series.push({data:data,name:name});
		})

		var barchart;
		barchart = new Highcharts.Chart({
			chart: {
				renderTo: id,
				defaultSeriesType: 'column',
				margin: [10, 0,80,60]
				//,
			//	type: 'spline'
			},
			xAxis: {categories:categories},
			series: series,
			colors: colors,
			yAxis: {
				title: {
            		text: ylabel,
            		style: {
						color: '#000000',
						fontWeight: 'normal'
					}
				},
				labels: {
					formatter: function() {
						return this.value + '%';
					}
				},
				endOnTick: true
        	},
        	tooltip: {
        		formatter: function() {
            		return '<b>' + this.series.name + '</b><br/>' + this.x + ': ' + number_format(this.y,2) + '%';
        		}
        	}
		});
	});



})



Highcharts.theme = {
	chart: {
		backgroundColor: "#F6F5F3",
		borderWidth: 0
	},
	title: {
		text: null
	},
	plotOptions: {
        series: {
            shadow: false,
            animation: false,
            events: {
            	legendItemClick: function(event) {return false} 
            }
        },
        column: {
            borderWidth: 0
        },
		pie: {
			size:'100%',
			allowPointSelect: false,
			dataLabels: { enabled: false }
		}

    },						
	tooltip: {
		formatter: function() {
			return '' + this.series.name +': '+ this.y +'%';
		}
	},
	credits: {
		enabled: false
	},
	yAxis: {
		endOnTick: false
	},
	legend: {
		layout: "vertical",
		backgroundColor: "#F6F5F3",
		borderRadius:0,
		align: "left",
		verticalAlign: "bottom",
		x: 40,
		y:0,
		itemStyle: {
			fontSize: "11px",
			color: '#333333'
		},
		itemHoverStyle: {
			color: '#333333'
		}
	},
	tooltip: {
		style: {
			fontSize: '10px'
		}
	}
};

var highchartsOptions = Highcharts.setOptions(Highcharts.theme);

function addCommas(nStr)
{
	nStr += '';
	x = nStr.split('.');
	x1 = x[0];
	x2 = x.length > 1 ? '.' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + ',' + '$2');
	}
	return x1 + x2;
}


// -------- helper functions --------- //

function number_format (number, decimals, dec_point, thousands_sep) {
    // Formats a number with grouped thousands  
    // 
    // version: 1109.2015
    // discuss at: http://phpjs.org/functions/number_format    // +   original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +     bugfix by: Michael White (http://getsprink.com)
    // +     bugfix by: Benjamin Lupton
    // +     bugfix by: Allan Jensen (http://www.winternet.no)    // +    revised by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
    // +     bugfix by: Howard Yeend
    // +    revised by: Luke Smith (http://lucassmith.name)
    // +     bugfix by: Diogo Resende
    // +     bugfix by: Rival    // +      input by: Kheang Hok Chin (http://www.distantia.ca/)
    // +   improved by: davook
    // +   improved by: Brett Zamir (http://brett-zamir.me)
    // +      input by: Jay Klehr
    // +   improved by: Brett Zamir (http://brett-zamir.me)    // +      input by: Amir Habibi (http://www.residence-mixte.com/)
    // +     bugfix by: Brett Zamir (http://brett-zamir.me)
    // +   improved by: Theriault
    // +      input by: Amirouche
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)    // *     example 1: number_format(1234.56);
    // *     returns 1: '1,235'
    // *     example 2: number_format(1234.56, 2, ',', ' ');
    // *     returns 2: '1 234,56'
    // *     example 3: number_format(1234.5678, 2, '.', '');    // *     returns 3: '1234.57'
    // *     example 4: number_format(67, 2, ',', '.');
    // *     returns 4: '67,00'
    // *     example 5: number_format(1000);
    // *     returns 5: '1,000'    // *     example 6: number_format(67.311, 2);
    // *     returns 6: '67.31'
    // *     example 7: number_format(1000.55, 1);
    // *     returns 7: '1,000.6'
    // *     example 8: number_format(67000, 5, ',', '.');    // *     returns 8: '67.000,00000'
    // *     example 9: number_format(0.9, 0);
    // *     returns 9: '1'
    // *    example 10: number_format('1.20', 2);
    // *    returns 10: '1.20'    // *    example 11: number_format('1.20', 4);
    // *    returns 11: '1.2000'
    // *    example 12: number_format('1.2000', 3);
    // *    returns 12: '1.200'
    // *    example 13: number_format('1 000,50', 2, '.', ' ');    // *    returns 13: '100 050.00'
    // Strip all characters but numerical ones.
    number = (number + '').replace(/[^0-9+\-Ee.]/g, '');
    var n = !isFinite(+number) ? 0 : +number,
        prec = !isFinite(+decimals) ? 0 : Math.abs(decimals),        sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep,
        dec = (typeof dec_point === 'undefined') ? '.' : dec_point,
        s = '',
        toFixedFix = function (n, prec) {
            var k = Math.pow(10, prec);            return '' + Math.round(n * k) / k;
        };
    // Fix for IE parseFloat(0.55).toFixed(0) = 0;
    s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.');
    if (s[0].length > 3) {        s[0] = s[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, sep);
    }
    if ((s[1] || '').length < prec) {
        s[1] = s[1] || '';
        s[1] += new Array(prec - s[1].length + 1).join('0');    }
    return s.join(dec);
}
