var wait = 0;
var enCours = 0;
var ad_wait = 0;
var ad_enCours = 0;
var footer_wait = 0;
var footer_enCours = 0;

function showDiv(divId)
{
	$(".js_shown").not('#'+divId).fadeOut(600 , function ()
		{
			$("#" + divId).removeClass('js_hidden').addClass("js_shown").fadeIn(600);
			$(this).removeClass('js_shown').addClass("js_hidden");
							   
		}
	);
};

function resetWait()
{
	wait = 0;
}

function resetAdWait()
{
	ad_wait = 0;
}

function resetFooterWait()
{
	footer_wait = 0;
}

function showSection(i, r)
{
	//if(r === undefined)
	if(typeof r === 'undefined')
	{
		r = true;
	}
	if(r)
	{
		wait = 1;
		setTimeout('resetWait()', 7000);
	}
    enCours = enCours + 1;
    //console.log('En cours : '+ enCours);
    var curId = $('.js_shown').attr('id');
	if(typeof curId === 'undefined')
	{
		return false;
	}
	else
	{
		if(curId != 'js_section' + i && enCours == 1)
		{
	/*			$('#' + curId).hide('slide', { direction: 'left' }, 500, function() {
				$('#js_section' + i).addClass('js_shown');
				$('#js_section' + i).removeClass('js_hidden');
				$('#js_section' + i).show('slide', { direction: 'right' }, 500);
				$('#' + curId).addClass('js_hidden');
				$('#' + curId).removeClass('js_shown');
			});*/
			var test = curId.indexOf('js_subSection');
			if(test != -1)
			{
				curId = curId.substr(13);
			}
			else
			{
			curId = curId.substr(10);
			}
			$('#js_section' + curId).fadeOut('normal', function()
				{
					$('#js_section' + i).fadeIn('normal');
					$('#js_section' + i).addClass('js_shown');
					$('#js_section' + i).removeClass('js_hidden');
					$('#js_section' + curId).removeClass('js_shown');
					$('#js_section' + curId).addClass('js_hidden');
					//$('.js_shown').attr('style', 'display: block;');
					$('.js_shown').css('display', 'block');
					enCours = 0;
				}
			);
			$('#js_subSection' + curId).fadeOut('normal', function()
				{
					$('#js_subSection' + i).fadeIn('normal');
				}
			);
		}
		else if (curId == 'js_section' + i)
		{
		   enCours = 0;
		}
	}
}

function billboard(j, speed)
{
	if(wait == 1)
	{
		setTimeout('billboard(' + j + ',' + speed + ')', 1000);
	}
	else
	{
		var newId = j + 1;
		if(!document.getElementById('js_section' + newId))
		{
			newId = 0;
		}
		showSection(newId, false);
		setTimeout('billboard(' + newId + ', ' + speed + ')', speed);
	}
}

function showAdSection(i, r)
{
	//if(r === undefined)
	if(typeof r === 'undefined')
	{
		r = true;
	}
	if(r)
	{
		ad_wait = 1;
		setTimeout('resetAdWait()', 10000);
	}
    ad_enCours = ad_enCours + 1;
    //console.log('En cours : '+ enCours);
    var curId = $('.js_ad_shown').attr('id');
	if(typeof curId === 'undefined')
	{
		return false;
	}
	else
	{
		if(curId != 'js_ad_section' + i && ad_enCours == 1)
		{
/*			$('#' + curId).hide('slide', { direction: 'left' }, 500, function() {
				$('#js_section' + i).addClass('js_shown');
				$('#js_section' + i).removeClass('js_hidden');
				$('#js_section' + i).show('slide', { direction: 'right' }, 500);
				$('#' + curId).addClass('js_hidden');
				$('#' + curId).removeClass('js_shown');
			});*/
			var ad_test = curId.indexOf('js_ad_subSection');
			if(ad_test != -1)
			{
				curId = curId.substr(16);
			}
			else
			{
				curId = curId.substr(13);
			}
			$('#js_ad_section' + curId).fadeOut('normal', function()
				{
					$('#js_ad_section' + i).fadeIn('normal');
					$('#js_ad_section' + i).addClass('js_ad_shown');
					$('#js_ad_section' + i).removeClass('js_ad_hidden');
					$('#js_ad_section' + curId).removeClass('js_ad_shown');
					$('#js_ad_section' + curId).addClass('js_ad_hidden');
					//$('.js_shown').attr('style', 'display: block;');
					$('.js_ad_shown').css('display', 'block');
					ad_enCours = 0;
				}
			);
			$('#js_ad_subSection' + curId).fadeOut('normal', function()
				{
					$('#js_ad_subSection' + i).fadeIn('normal');
				}
			);
		}
		else if (curId == 'js_ad_section' + i)
		{
		   ad_enCours = 0;
		}
	}
}

function advertisement(j, speed)
{
	if(ad_wait == 1)
	{
		setTimeout('advertisement(' + j + ',' + speed + ')', 1000);
	}
	else
	{
		var newId = j + 1;
		if(!document.getElementById('js_ad_section' + newId))
		{
			newId = 0;
		}
		showAdSection(newId, false);
		setTimeout('advertisement(' + newId + ', ' + speed + ')', speed);
	}
}

function showFooterSection(i, r)
{
	//if(r === undefined)
	if(typeof r === 'undefined')
	{
		r = true;
	}
	if(r)
	{
		footer_wait = 1;
		setTimeout('resetFooterWait()', 7000);
	}
    footer_enCours = footer_enCours + 1;
    //console.log('En cours : '+ enCours);
    var curId = $('.js_footer_shown').attr('id');
	if(curId != 'js_footer_section' + i && footer_enCours == 1) {
/*			$('#' + curId).hide('slide', { direction: 'left' }, 500, function() {
			$('#js_section' + i).addClass('js_shown');
			$('#js_section' + i).removeClass('js_hidden');
			$('#js_section' + i).show('slide', { direction: 'right' }, 500);
			$('#' + curId).addClass('js_hidden');
			$('#' + curId).removeClass('js_shown');
		});*/
		var footer_test = curId.indexOf('js_footer_subSection');
		if(footer_test != -1)
		{
			curId = curId.substr(20);
		}
		else
		{
			curId = curId.substr(17);
		}
		$('#js_footer_section' + curId).fadeOut('normal', function()
			{
				$('#js_footer_section' + i).fadeIn('normal');
				$('#js_footer_section' + i).addClass('js_footer_shown');
				$('#js_footer_section' + i).removeClass('js_footer_hidden');
				$('#js_footer_section' + curId).removeClass('js_footer_shown');
				$('#js_footer_section' + curId).addClass('js_footer_hidden');
				//$('.js_shown').attr('style', 'display: block;');
				$('.js_footer_shown').css('display', 'block');
				footer_enCours = 0;
			}
		);
		$('#js_footer_subSection' + curId).fadeOut('normal', function()
			{
				$('#js_footer_subSection' + i).fadeIn('normal');
			}
		);
	}
	else if (curId == 'js_footer_section' + i)
	{
	   footer_enCours = 0;
	}
}

function partners(j, speed)
{
	if(footer_wait == 1)
	{
		setTimeout('partners(' + j + ',' + speed + ')', 1000);
	}
	else
	{
		var newId = j + 1;
		if(!document.getElementById('js_footer_section' + newId))
		{
			newId = 0;
		}
		showFooterSection(newId, false);
		setTimeout('partners(' + newId + ', ' + speed + ')', speed);
	}
}

function starter(speed)
{
	/*var ct = 0;
	while(document.getElementById('js_section' + ct))
	{
		ct++;
	}
	var start = Math.floor(Math.random() * ct);*/
	wait = 1;
	setTimeout('resetWait()', 7000);
	billboard(0, speed);
	ad_wait = 1;
	setTimeout('resetAdWait()', 10000);
	advertisement(0, 10000);
	footer_wait = 1;
	setTimeout('resetFooterWait()', 7000);
	partners(0, speed);
}

jQuery(function($)
{
	/* afficher cacher */		
	$('.js_menu a[href^=#]').click(function()
	{				
		toggleSection(this);
				
		if(!$.browser.msie)
		{
			//update the hash
			var name =  $(this).attr('href').substring(1);
			var anchor = $('a[name="' +name + '"]');
			anchor.attr('name', name+'_temp');
			window.location.hash = $(this).attr('href');	
			anchor.attr('name', name);			
		}
		return false;				
	});
			
	/**/
	/*location change*/
	if($('.js_menu').length > 0)
	{
		$.history.init(function()
		{	
			var page = location.hash.substring(1);
			
			if(page != '' && $("a[href=#" + page + "]").length > 0)
			{           
				//$('.js_menu a[href="#' + page + '"]').click();
				toggleSection($('.js_menu a[href="#' + page + '"]'));
			}
			else
			{
				$('.collapsible:first').show();
				$('.js_menu a').removeClass('active');
				$('.js_menu a:first').addClass('active');
			}
		});
	}
});

function toggleSection(obj)
{
	var idx = $('.js_menu a[href^=#]').removeClass('active').index(obj);				
	$(obj).addClass('active');
	$('.collapsible').hide();				
	$('.collapsible').eq(idx).show();
}


/* ----- Calculateurs ----- */


function reverseString(e)
{
	var i = e.length;
	i = i-1;

	var f = '';
	
	for(var x = i; x >= 0; x--)
	{
		f = f + e.charAt(x);
	}
	
	return f;
}

function convertComma(e)
{
	e = e.toString();
	e = e.split('.');
	
	e[0] = reverseString(e[0]);
	e[0] = e[0].replace(/(\S{3})/g,"$1 ");
	e[0] = e[0].replace(/ $/,"");
	e[0] = reverseString(e[0]);
	
	e = e.join(',');
	
	return e;
}
function clearInput(input){
	if(getCleanData(input.value)==0)
		input.value='';
}
function getCleanData(e)
{
	e = e.split(' ').join('');
	e = e.split('$').join('');
	e = e.split('%').join('');
	e = e.split(',').join('.');
	e = parseFloat(e);
	if(isNaN(e)){
		e = 0;
	}
	e = roundNumber(e, 2);
	
	return e;
}
function toMoney(n, dec){
	if(typeof dec == 'undefined')
		dec =2;
	var decimalSeparator = ','; //Number("1.2").toLocaleString().substr(1,1);
	//m = n.toLocaleString().split(DecimalSeparator)[0];
	var t = ' ';
	var sign = (n < 0) ? '-' : '';
	var i = parseInt(n = Math.abs(n).toFixed(dec)) + '';
  var j = ((j = i.length) > 3) ? j % 3 : 0; 
	var m = sign + (j ? i.substr(0, j) + t : '') + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (dec ? decimalSeparator + Math.abs(n - i).toFixed(dec).slice(2) : ''); 
	return m + " $";

}
function roundNumber(num, dec)
{
	//var result = Math.round(num*Math.pow(10,dec))/Math.pow(10,dec);
	var result = num.toFixed(dec);
	return result;
}

function roundOver(num, zeros)
{
	zeros--;
	var round_multiplier = 1;
	for(var e = 0; e < zeros; e++)
	{
		round_multiplier = round_multiplier + '0';
	}
	num = num / round_multiplier;
	num = roundNumber(num, 0);
	num = num * round_multiplier;
	
	return num;
}

function formatNumber(e)
{
	if((typeof(e) == 'number') && (e.toString().indexOf('.') == -1))
	{
		e = e + '.00';
	}
	else
	{
		var length = e.toString().length;
		if(e.toString().indexOf('.') == length - 2)
		{
			e = e + '0';
		}
	}
	
	return e;
}

function getTicks(max_val)
{
	max_len = String(max_val).length;
	max_len--;
	var step = Math.pow(10, max_len);
	var round = max_len;
	var max = roundOver(max_val, round);
	if(max_val > max)
	{
		max = max + step;
	}
	if(max == step)
	{
		step = step / 5;
	}
	if(max < (3 * step) && max != step)
	{
		step = step / 2;
	}
	return step;
}

function populateList(i)
{
	var j = 1;
	while(j < i)
	{
		if($("#since option[value='" + j + "']").length == 0)
		{
			$("#since").append($('<option></option>').val(j).html(j + ' ans'));
		}
		j++;
	}
	while($("#since option[value='" + j + "']").length != 0)
	{
		$("#since option[value='" + j + "']").remove();
		j++;
	}
}

function showRates(i)
{
	var j = 1;
	while(j <= i)
	{
		$('#rate_ctn_' + j).show();
		j++;
	}
	while(j <= 11)
	{
		$('#rate_ctn_' + j).hide();
		j++;
	}
}

function timeIsMoney()
{
	var invested = parseFloat(getCleanData(document.getElementById('stock').value));
	var investment = parseFloat(getCleanData(document.getElementById('investment').value));
	var rate = parseFloat(getCleanData(document.getElementById('interest').value)) / 100;
	var duration = parseInt(getCleanData(document.getElementById('duration').value));
	col_a = 0;
	var col_b = 0;
	var col_c = 0;
	var col_d = 0;
	
	if(rate == 0)
	{
		col_a = invested + investment * 5;
	}
	else
	{
		var pct_rate = rate + 1;
		col_a = pct_rate * investment * (Math.pow(pct_rate, 5) - 1) / rate + invested * Math.pow(pct_rate, 5);
	}
	
	if(rate == 0)
	{
		col_b = invested + investment * 10;
	}
	else
	{
		var pct_rate = rate + 1;
		col_b = pct_rate * investment * (Math.pow(pct_rate, 10) - 1) / rate + invested * Math.pow(pct_rate, 10);
	}
	
	if(rate == 0)
	{
		col_c = invested + investment * 25;
	}
	else
	{
		var pct_rate = rate + 1;
		col_c = pct_rate * investment * (Math.pow(pct_rate, 25) - 1) / rate + invested * Math.pow(pct_rate, 25);
	}
	
	if(rate == 0)
	{
		col_d = invested + investment * duration;
	}
	else
	{
		var pct_rate = rate + 1;
		col_d = pct_rate * investment * (Math.pow(pct_rate, duration) - 1) / rate + invested * Math.pow(pct_rate, duration);
	}
	
	var min_value = col_a;
	if(col_b < min_value)
	{
		min_value = col_b;
	}
	if(col_c < min_value)
	{
		min_value = col_c;
	}
	if(col_d < min_value)
	{
		min_value = col_d;
	}
	var max_value = col_a;
	if(col_b > max_value)
	{
		max_value = col_b;
	}
	if(col_c > max_value)
	{
		max_value = col_c;
	}
	if(col_d > max_value)
	{
		max_value = col_d;
	}
	min_value = Math.floor(min_value);
	var min_length = String(min_value).length;
	if(min_length > 4)
	{
		min_value = 0;
	}
	else
	{
		var k = 0;
		var multiplier = 1;
		for(k = 0; k < min_length - 1; k++)
		{
			multiplier = multiplier + '0';
		}
		min_value = Math.floor(min_value / multiplier);
		min_value = min_value * multiplier;
	}
	max_value = Math.ceil((max_value * 110) / 100);
	
	var step = getTicks(max_value);
	var tick_list = new Array();
	var i = 0;
	var j = 0;
	while(i < max_value)
	{
		tick_list[j] = i;
		i = i + step;
		j++;
	}
	tick_list[j] = i;
	
	// Config chart bars and x-axis legend
	line1 = [col_a, col_b, col_c, col_d];
	
	if(duration == 1)
	{
		duration = '1 an';
	}
	else
	{
		duration = duration + ' ans';
	}
	
	col_a = toMoney(col_a, 0);
	col_b = toMoney(col_b, 0);
	col_c = toMoney(col_c, 0);
	col_d = toMoney(col_d, 0);
	

	document.getElementById('stock').value = convertComma(formatNumber(roundNumber(invested, 2))) + ' $';
	document.getElementById('investment').value = convertComma(formatNumber(roundNumber(investment, 2))) + ' $';
	document.getElementById('interest').value = convertComma(formatNumber(roundNumber(rate * 100, 2))) + ' %';
	document.getElementById('5yr').innerHTML = col_a;
	document.getElementById('10yr').innerHTML = col_b;
	document.getElementById('25yr').innerHTML = col_c;
	document.getElementById('custom').innerHTML = col_d;
	document.getElementById('result_duration').innerHTML = duration;
	
	document.getElementById('chartdiv').innerHTML = '';
	
	$.jqplot.config.enablePlugins = true;
	
	plot1 = $.jqplot('chartdiv', [line1], {
		seriesColors: ["#cbd422", "#cbd422", "#cbd422", "#1bb1e7"],
		legend:{show:false, location:'nw', xoffset:55},
		grid: {
			drawGridLines: true,        // wether to draw lines across the grid or not.
			gridLineColor: '#ffffff',    // *Color of the grid lines.
			background: '#e5e5e5',      // CSS color spec for background color of grid.
			borderColor: '#e5e5e5',     // CSS color spec for border around grid.
			borderWidth: 2,           // pixel width of border around grid.
			shadow: false,               // draw a shadow for grid.
			shadowAngle: 45,            // angle of the shadow.  Clockwise from x axis.
			shadowOffset: 1.5,          // offset from the line of the shadow.
			shadowWidth: 3,             // width of the stroke for the shadow.
			shadowDepth: 3,             // Number of strokes to make when drawing shadow.
										// Each stroke offset by shadowOffset from the last.
			shadowAlpha: 0.07,           // Opacity of the shadow
			renderer: $.jqplot.CanvasGridRenderer,  // renderer to use to draw the grid.
			rendererOptions: {}         // options to pass to the renderer.  Note, the default
                                    // CanvasGridRenderer takes no additional options.
		},
		seriesDefaults:{
			renderer:$.jqplot.BarRenderer,
			rendererOptions: {
				barPadding: 8,      // number of pixels between adjacent bars in the same
									// group (same category or bin).
				barMargin: 48,      // number of pixels between adjacent groups of bars.
				barDirection: 'vertical', // vertical or horizontal.
				barWidth: null,     // width of the bars.  null to calculate automatically.
				shadow: false,               // draw a shadow for grid.
				shadowOffset: 2,    // offset from the bar edge to stroke the shadow.
				shadowDepth: 5,     // nuber of strokes to make for the shadow.
				shadowAlpha: 0.8,   // transparency of the shadow.
				varyBarColor: true
			}
		},
		series:[
			{			
				pointLabels:
				{
					labels:[col_a, col_b, col_c, col_d]
				}
			}
		],
		axes:{
			xaxis:{				
				renderer:$.jqplot.CategoryAxisRenderer, 
				ticks:['5 ans', '10 ans', '25 ans', duration],
				tickOptions: {
					showGridline: false // wether to draw a gridline (across the whole grid) at this tick,
				}
			}, 
			yaxis:{		
				ticks: tick_list,
				/*autoscale: true,*/
				tickOptions:{
					formatString:'%d',
					mark: false,
					formatter: MoneyTickFormatter
				},
				min: 0
			}
		}
	});
}

function progressiveInvestment()
{
	var investment = parseFloat(getCleanData(document.getElementById('investment').value));
	var duration = parseInt(getCleanData(document.getElementById('duration').value));
	var since = parseInt(getCleanData(document.getElementById('since').value));
	
	populateList(duration);
	showRates(duration);
	
	var i = 1;
	var j = 0;
	var values = new Array();
	while(j < duration)
	{
		values[i] = parseFloat(getCleanData(document.getElementById('rate_' + i).value));
		document.getElementById('rate_' + i).value = convertComma(formatNumber(values[i])) + ' %';
		i++;
		j++;
	}
	
	var yield = new Array();
	yield[1] = (1 + values[1]/100);
	i = 2;
	j = 1;
	while(i <= duration)
	{
		yield[i] = (1 + (values[i] /100)) * yield[j];
		i++;
		j++;
	}
	
	var average = new Array();
	average[0] = 0;
	average[1] = values[1];
	i = 2;
	j = 1;
	while(i <= duration)
	{
		average[i] = (Math.pow(yield[i], 1 / i) - 1) * 100;
		i++;
		j++;
	}
	
	var money = new Array();
	money[0] = investment;
	money[1] = investment * (1 + values[1] / 100);
	i = 2;
	j = 1;
	while(i <= duration)
	{
		money[i] = money[j] * (1 + values[i] / 100);
		i++;
		j++;
	}
	
	var rate_average = 1 + average[duration] / 100;
	var rate_since = 1 + average[since] / 100;
	var yrs_diff = duration - since;
	
	var needed = (Math.pow(Math.pow(rate_average, duration) / Math.pow(rate_since, since), 1 / yrs_diff) - 1) * 100;
	
	document.getElementById('investment').value = convertComma(formatNumber(investment) + ' $');
	document.getElementById('average').innerHTML = convertComma(formatNumber(roundNumber(average[duration], 3)) + ' %');
	if(since > duration)
	{
		since = 0;
	}
	document.getElementById('achieved').innerHTML = convertComma(formatNumber(roundNumber(average[0], 3)) + ' %');
	document.getElementById('achieved').innerHTML = convertComma(formatNumber(roundNumber(average[since], 3)) + ' %');
	document.getElementById('needed').innerHTML = convertComma(formatNumber(roundNumber(needed, 3)) + ' %');
	document.getElementById('present').innerHTML = convertComma(formatNumber(roundNumber(money[since], 2)) + ' $');
	document.getElementById('future').innerHTML = convertComma(formatNumber(roundNumber(money[duration], 2)) + ' $');
	
	/*if(since != 0)
	{
		since = since + 0.5;
	}
	else
	{
		yrs_diff = yrs_diff + 0.5;
	}*/
	
	var line1 = [[since, 1]];
	var line2 = [[yrs_diff, 1]];
	
	document.getElementById('chartdiv').innerHTML = '';
	
	$.jqplot.config.enablePlugins = true;
	
	plot1 = $.jqplot('chartdiv', [line1, line2], {
		seriesColors: ["#cbd422", "#1bb1e7"],
		stackSeries: true,
		legend:{show:false, location:'ne'},
		grid: {
			drawGridLines: true,        // wether to draw lines across the grid or not.
			gridLineColor: '#ffffff',    // *Color of the grid lines.
			background: '#e5e5e5',      // CSS color spec for background color of grid.
			borderColor: '#e5e5e5',     // CSS color spec for border around grid.
			borderWidth: 2,           // pixel width of border around grid.
			shadow: false,               // draw a shadow for grid.
			renderer: $.jqplot.CanvasGridRenderer,  // renderer to use to draw the grid.
			rendererOptions: {}         // options to pass to the renderer.  Note, the default
                                    // CanvasGridRenderer takes no additional options.
		},
		axesDefaults:{
			tickOptions: {
				showGridline: false // wether to draw a gridline (across the whole grid) at this tick,
			}
		},
		seriesDefaults:{
			yaxis: 'y2axis',
			renderer:$.jqplot.BarRenderer,
			rendererOptions: {
				barPadding: 8,      // number of pixels between adjacent bars in the same group (same category or bin).
				barMargin: 70,      // number of pixels between adjacent groups of bars.
				barDirection: 'horizontal', // vertical or horizontal.
				barWidth: null,     // width of the bars.  null to calculate automatically.
				shadow: false              // draw a shadow for grid.
			},
			showMarker: false
		},
		series:[
			{
				pointLabels:
				{
					show:false
				}
			}
		],
		axes:{
			xaxis:{
				/*renderer:$.jqplot.CategoryAxisRenderer,*/
				/*ticks:['0', '1 an', '2 ans', '3 ans', '4 ans', '5 ans', '6 ans', '7 ans', '8 ans', '9 ans', '10 ans'],*/
				tickOptions: {
					showGridline: true, // wether to draw a gridline (across the whole grid) at this tick,
					mark: false,
					formatString: '%d'
				},
				min: 0,
				max: 10,
				numberTicks: 11
			},
			y2axis:{
				showTicks: false
			}
		}
	});
	
	$('.jqplot-point-label').remove();
}

function yield()
{
	var investment = parseFloat(getCleanData(document.getElementById('investment').value));
	var duration = parseInt(getCleanData(document.getElementById('duration').value));
	var rate = parseFloat(getCleanData(document.getElementById('rate').value)) / 100;
	if(rate > 0.4)
	{
		rate = 0.4;
	}
	var col_a = 0;
	var  col_b = 0;
	var col_c = 0;
	var col_d = 0;
	
	var coeff = rate + 1;
	
	col_a = (1.03 * investment * (Math.pow(1.03, duration) - 1) / 0.03);
	col_b = (1.05 * investment * (Math.pow(1.05, duration) - 1) / 0.05);
	col_c = (1.07 * investment * (Math.pow(1.07, duration) - 1) / 0.07);
	if(rate == 0)
	{
		col_d = investment * duration;
	}
	else
	{
		col_d = (coeff * investment * (Math.pow(coeff, duration) - 1) / rate);
	}
	
	line1 = [col_a, col_b, col_c, col_d];
	col_a_f = toMoney(col_a);
	col_b_f = toMoney(col_b);
	col_c_f = toMoney(col_c);
	col_d_f = toMoney(col_d);
	
	var min_value = col_a;
	if(col_b < min_value)
	{
		min_value = col_b;
	}
	if(col_c < min_value)
	{
		min_value = col_c;
	}
	if(col_d < min_value)
	{
		min_value = col_d;
	}
	var max_value = col_a;
	if(col_b > max_value)
	{
		max_value = col_b;
	}
	if(col_c > max_value)
	{
		max_value = col_c;
	}
	if(col_d > max_value)
	{
		max_value = col_d;
	}
	min_value = Math.floor(min_value);
	var min_length = String(min_value).length;
	if(min_length > 4)
	{
		min_value = 0;
	}
	else
	{
		var k = 0;
		var multiplier = 1;
		for(k = 0; k < min_length - 1; k++)
		{
			multiplier = multiplier + '0';
		}
		min_value = Math.floor(min_value / multiplier);
		min_value = min_value * multiplier;
	}
	
	var scale_max = max_value - min_value;
	scale_max = Math.ceil((scale_max * 110) / 100);
	var step = getTicks(scale_max);
	var tick_list = new Array();
	var i = min_value;
	var j = 0;
	while(i < (min_value + scale_max))
	{
		tick_list[j] = i;
		i = i + step;
		j++;
	}
	tick_list[j] = i;
	
	document.getElementById('investment').value = convertComma(roundNumber(investment, 2) + ' $');
	document.getElementById('rate').value = convertComma(roundNumber(rate * 100, 3) + ' %');
	document.getElementById('result_rate').innerHTML = convertComma(roundNumber(rate * 100, 3) + ' %');
	document.getElementById('3pct').innerHTML = col_a_f;
	document.getElementById('5pct').innerHTML = col_b_f;
	document.getElementById('7pct').innerHTML = col_c_f;
	document.getElementById('custom').innerHTML = col_d_f;
	
	document.getElementById('chartdiv').innerHTML = '';
	
	$.jqplot.config.enablePlugins = true;
	
	plot1 = $.jqplot('chartdiv', [line1], {
		seriesColors: ["#cbd422", "#cbd422", "#cbd422", "#1bb1e7"],
		legend:{show:false, location:'nw', xoffset:55},
		grid: {
			drawGridLines: true,        // wether to draw lines across the grid or not.
			gridLineColor: '#ffffff',    // *Color of the grid lines.
			background: '#e5e5e5',      // CSS color spec for background color of grid.
			borderColor: '#e5e5e5',     // CSS color spec for border around grid.
			borderWidth: 2,           // pixel width of border around grid.
			shadow: false,               // draw a shadow for grid.
			shadowAngle: 45,            // angle of the shadow.  Clockwise from x axis.
			shadowOffset: 1.5,          // offset from the line of the shadow.
			shadowWidth: 3,             // width of the stroke for the shadow.
			shadowDepth: 3,             // Number of strokes to make when drawing shadow.
										// Each stroke offset by shadowOffset from the last.
			shadowAlpha: 0.07,           // Opacity of the shadow
			renderer: $.jqplot.CanvasGridRenderer,  // renderer to use to draw the grid.
			rendererOptions: {}         // options to pass to the renderer.  Note, the default
                                    // CanvasGridRenderer takes no additional options.
		},
		seriesDefaults:{
			renderer:$.jqplot.BarRenderer,
			rendererOptions: {
				barPadding: 8,      // number of pixels between adjacent bars in the same
									// group (same category or bin).
				barMargin: 48,      // number of pixels between adjacent groups of bars.
				barDirection: 'vertical', // vertical or horizontal.
				barWidth: null,     // width of the bars.  null to calculate automatically.
				shadow: false,               // draw a shadow for grid.
				shadowOffset: 2,    // offset from the bar edge to stroke the shadow.
				shadowDepth: 5,     // nuber of strokes to make for the shadow.
				shadowAlpha: 0.8,   // transparency of the shadow.
				varyBarColor: true
			}
		},
		series:[
			{
				pointLabels:
				{
					Labels:[col_a_f, col_b_f, col_c_f, col_d_f]
				}
			}
		],
		axes:{
			xaxis:{
				renderer:$.jqplot.CategoryAxisRenderer, 
				ticks:['3 %', '5 %', '7 %', convertComma(roundNumber(rate * 100, 3) + ' %')],
				tickOptions: {
					showGridline: false // wether to draw a gridline (across the whole grid) at this tick,
				}
			}, 
			yaxis:{
				ticks: tick_list,
				/*autoscale:true,*/
				tickOptions:{
					formatString:'%d',
					mark: false,
					formatter: MoneyTickFormatter
				},
				min: min_value
			}
		}
	});
}

function timeIsMoneyInflation()
{
	var invested = parseFloat(getCleanData(document.getElementById('stock').value));
	var investment = parseFloat(getCleanData(document.getElementById('investment').value));
	var inflation = parseFloat(getCleanData(document.getElementById('inflation').value)) / 100;
	var rate = parseFloat(getCleanData(document.getElementById('interest').value)) / 100;
	var duration = parseInt(getCleanData(document.getElementById('duration').value));
	col_a = 0;
	var col_b = 0;
	var col_c = 0;
	var col_d = 0;
	
	if(inflation > rate)
	{
		alert('L\'inflation ne peut être supérieure au rendement.');
		inflation = rate;
	}
	
	var pct_rate = ((rate + 1) / (inflation + 1));
	var net_rate = pct_rate - 1;
		
	if(net_rate == 0)
	{
		col_a = invested + investment * 5;
	}
	else
	{
		col_a = pct_rate * investment * (Math.pow(pct_rate, 5) - 1) / net_rate + invested * Math.pow(pct_rate, 5);
	}
	
	if(net_rate == 0)
	{
		col_b = invested + investment * 10;
	}
	else
	{
		col_b = pct_rate * investment * (Math.pow(pct_rate, 10) - 1) / net_rate + invested * Math.pow(pct_rate, 10);
	}
	
	if(net_rate == 0)
	{
		col_c = invested + investment * 25;
	}
	else
	{
		col_c = pct_rate * investment * (Math.pow(pct_rate, 25) - 1) / net_rate + invested * Math.pow(pct_rate, 25);
	}
	
	if(net_rate == 0)
	{
		col_d = invested + investment * duration;
	}
	else
	{
		col_d = pct_rate * investment * (Math.pow(pct_rate, duration) - 1) / net_rate + invested * Math.pow(pct_rate, duration);
	}
	
	var min_value = col_a;
	if(col_b < min_value)
	{
		min_value = col_b;
	}
	if(col_c < min_value)
	{
		min_value = col_c;
	}
	if(col_d < min_value)
	{
		min_value = col_d;
	}
	var max_value = col_a;
	if(col_b > max_value)
	{
		max_value = col_b;
	}
	if(col_c > max_value)
	{
		max_value = col_c;
	}
	if(col_d > max_value)
	{
		max_value = col_d;
	}
	min_value = Math.floor(min_value);
	var min_length = String(min_value).length;
	if(min_length > 4)
	{
		min_value = 0;
	}
	else
	{
		var k = 0;
		var multiplier = 1;
		for(k = 0; k < min_length - 1; k++)
		{
			multiplier = multiplier + '0';
		}
		min_value = Math.floor(min_value / multiplier);
		min_value = min_value * multiplier;
	}
	max_value = Math.ceil((max_value * 110) / 100);
	
	var step = getTicks(max_value);
	var tick_list = new Array();
	var i = 0;
	var j = 0;
	while(i < max_value)
	{
		tick_list[j] = i;
		i = i + step;
		j++;
	}
	tick_list[j] = i;
	
	// Config chart bars and x-axis legend
	line1 = [col_a, col_b, col_c, col_d];
	
	if(duration == 1)
	{
		duration = '1 an';
	}
	else
	{
		duration = duration + ' ans';
	}
	
	col_a = toMoney(col_a, 0);
	col_b = toMoney(col_b, 0);
	col_c = toMoney(col_c, 0);
	col_d = toMoney(col_d, 0);
	

	document.getElementById('stock').value = convertComma(formatNumber(roundNumber(invested, 2))) + ' $';
	document.getElementById('investment').value = convertComma(formatNumber(roundNumber(investment, 2))) + ' $';
	document.getElementById('interest').value = convertComma(formatNumber(roundNumber(rate * 100, 2))) + ' %';
	document.getElementById('inflation').value = convertComma(formatNumber(roundNumber(inflation * 100, 2))) + ' %';
	document.getElementById('5yr').innerHTML = col_a;
	document.getElementById('10yr').innerHTML = col_b;
	document.getElementById('25yr').innerHTML = col_c;
	document.getElementById('custom').innerHTML = col_d;
	document.getElementById('result_duration').innerHTML = duration;
	
	document.getElementById('chartdiv').innerHTML = '';
	
	$.jqplot.config.enablePlugins = true;
	
	plot1 = $.jqplot('chartdiv', [line1], {
		seriesColors: ["#cbd422", "#cbd422", "#cbd422", "#1bb1e7"],
		legend:{show:false, location:'nw', xoffset:55},
		grid: {
			drawGridLines: true,        // wether to draw lines across the grid or not.
			gridLineColor: '#ffffff',    // *Color of the grid lines.
			background: '#e5e5e5',      // CSS color spec for background color of grid
			borderColor: '#e5e5e5',     // CSS color spec for border around grid.
			borderWidth: 2,           // pixel width of border around grid.
			shadow: false,               // draw a shadow for grid.
			shadowAngle: 45,            // angle of the shadow.  Clockwise from x axis.
			shadowOffset: 1.5,          // offset from the line of the shadow.
			shadowWidth: 3,             // width of the stroke for the shadow.
			shadowDepth: 3,             // Number of strokes to make when drawing shadow.
										// Each stroke offset by shadowOffset from the last.
			shadowAlpha: 0.07,           // Opacity of the shadow
			renderer: $.jqplot.CanvasGridRenderer,  // renderer to use to draw the grid.
			rendererOptions: {}         // options to pass to the renderer.  Note, the default
                                    // CanvasGridRenderer takes no additional options.
		},
		seriesDefaults:{
			renderer:$.jqplot.BarRenderer,
			rendererOptions: {
				barPadding: 8,      // number of pixels between adjacent bars in the same
									// group (same category or bin).
				barMargin: 48,      // number of pixels between adjacent groups of bars.
				barDirection: 'vertical', // vertical or horizontal.
				barWidth: null,     // width of the bars.  null to calculate automatically.
				shadow: false,               // draw a shadow for grid.
				shadowOffset: 2,    // offset from the bar edge to stroke the shadow.
				shadowDepth: 5,     // nuber of strokes to make for the shadow.
				shadowAlpha: 0.8,   // transparency of the shadow.
				varyBarColor: true
			}
		},
		series:[
			{			
				pointLabels:
				{
					labels:[col_a, col_b, col_c, col_d]
				}
			}
		],
		axes:{
			xaxis:{				
				renderer:$.jqplot.CategoryAxisRenderer, 
				ticks:['5 ans', '10 ans', '25 ans', duration],
				tickOptions: {
					showGridline: false // wether to draw a gridline (across the whole grid) at this tick,
				}
			}, 
			yaxis:{		
				ticks: tick_list,
				/*autoscale: true,*/
				tickOptions:{
					formatString:'%d',
					mark: false,
					formatter: MoneyTickFormatter
				},
				min: 0
			}
		}
	});
}

function MoneyTickFormatter(format, val){
	 if(format=='%d' && typeof val =='number'){
		return toMoney(val, 0);
	 }else{
		return $.jqplot.DefaultTickFormatter(format, val);
	 }
}

$(document).ready(function(){
	//select all the a tag with name equal to modal
	$('a[name=modal]').click(function(e)
	{
		//Cancel the link behavior
		e.preventDefault();
		
		//Get the A tag
		var id = $(this).attr('href');
		
		//Scroll to top
		if ( document.documentElement && document.documentElement.scrollTop )
		{
			document.documentElement.scrollTop = 0;
		}
		else if ( document.body )
		{
			document.body.scrollTop = 0;
		}
	
		//Get the screen height and width
		var maskHeight = $(document).height();
		var maskWidth = $(window).width();
	
		//Set heigth and width to mask to fill up the whole screen
		$('#mask').css({'width':maskWidth,'height':maskHeight});
		
		//transition effect		
		$('#mask').fadeIn(1000);	
		$('#mask').fadeTo("slow",0.8);	
	
		//Get the window height and width
		var winH = $(window).height();
		var winW = $(window).width();
			  
		//Set the popup window to center
		$(id).css('top',  winH/2-$(id).height()/2);
		$(id).css('left', winW/2-$(id).width()/2);
	
		//transition effect
		$(id).fadeIn(2000);
	});

	//if close button is clicked
	$('.modal .close').click(function (e) {
		//Cancel the link behavior
		e.preventDefault();
		
		$('#mask').hide();
		$('.modal').hide();
	});		
	
	//if mask is clicked
	$('#mask').click(function () {
		$(this).hide();
		$('.modal').hide();
	});
});

function calcule_epargne(num,check)
{
	var total = 0;
	var epargne = parseInt(document.calculateur.epargneH.value);
	  
	if(document.calculateur[check].checked)
	{
		total = epargne+num;
	}
	else
	{
		total = epargne-num;
	}
	document.calculateur.epargneH.value = total + ' $';
	document.calculateur.epargneA.value = total * 52 + ' $';
}

