var ContractTables = new Array();
var LoaderUrl;
var $currencyInput;
var $volumeInput;
var $lengthInput;
var $timeInput;
var $typeInput;
$(function()
{
	$currencyInput = $('#ChartCurrency');
	$volumeInput = $('#ChartVolumeUnit');
	$lengthInput = $('#ChartPeriod');
	$timeInput = $('#ChartTimeUnit');
	$typeInput = $('#ChartType');
	
	//$("#ChartBasics input[name='data[Chart][data_type]']").click(updateAvaibleOptionsDivs);
	$('#ChartProductName').change(productNameChange).trigger('change');
	
	$('#ChartPeriod').change(updateTimeUnit).trigger('change');
	
	$('#ChartTimeUnit').change(updateChartType).trigger('change');
		
	$('#advancedOptions div.input.checkbox input[type="checkbox"]').click(handleBaseClick);
	
	$('#ChartCurrency').change(currencyChange);
	currencyChange();
	
	if($('#ChartFlashWrap').length)
	{
		LoaderUrl = $('#Chart').css('background-image');
		$('#Chart').css('background-image', 'none');
	}
	
	// Tabs
	$("#Charts .tab_content").hide(); //Hide all content
	$("#Charts ul.chartTabs li:first").addClass("active").show(); //Activate first tab
	$("#Charts .tab_content:first").show(); //Show first tab content
	
	$("#Charts ul.chartTabs li").click(changeTab)
	$("#Charts ul.chartTabs li#firstTab").click(function(){
		$('#ChartDataTypeContinuous').trigger('click')
		$('#ChartLength').trigger('change')
	})
	$("#Charts ul.chartTabs li#secondTab").click(function(){
		$('#ChartDataTypeContract').trigger('click');
		$('#ChartLength').trigger('change');
	})
	
	$('.ProductActiveContracts tr').click(ProductActiveContractsClick)
	
	$('#ChartCurrency, #ChartVolumeUnit').change(ChartUpdate)
	$('#refreshIcon').click(ChartUpdate)
	
	checkActiveTab();
	
	//Interraction with Product tables
	if($('.ProductActiveContracts').length)
	{	
		tmpCpt = 0;
		$('.ProductActiveContracts').each(function()
		{
			ContractTables[tmpCpt] = $(this).clone(true);
			tmpCpt++;
		});
		$('#TableCurrency').change(tableOptionChange);
		$('#TableVolumeUnit').change(tableOptionChange);
		tableOptionChange()
	}
	
	//Print chart
	if($('#printChart')) {
		$('#printChart a').click(function() {
			OFC.jquery.popup('ofchart');
			anTrack1('Prix et graphiques','Imprimer', window.document.title)
			return false;
		})
	}
})

function tableOptionChange()
{
	var currentId = $(this).attr('id');
	if( currentId == 'TableCurrency') 
	{
		anTrack1('Tableau','Devise',$('#TableCurrency').val())
	}
	else if(currentId == 'TableVolumeUnit') 
	{
		anTrack1('Tableau','Volume',$('#TableVolumeUnit').val())
	}
	//Defines currency rate
	currency = $('#TableCurrency').val().toUpperCase();
	currencyRate = parseFloat($('#SymCurr' + currency).attr('rel'));
	volumeUnit = $('#TableVolumeUnit').val();
	$('.infoMessage').hide();
	//Define volume rates
	if(volumeUnit == 'bushel')
	{
		nbDecimals = 4;
		volumeRate = 1;
	}	    
	else if(volumeUnit == 'st')
	{
		nbDecimals = 2;
		volumeRate = 1;
	}	 
	else if(volumeUnit == 'contract')
	{
		$('#' + productNameEn + 'ContractUnitNotice').show();
		nbDecimals = 0;
		volumeRate = 5000;    
		if (productNameEn == 'soybean-meal') 
		{
			volumeRate = 100
		}
	}
	else
	{
		nbDecimals = 2;
		volumeRate = 1/Convert.vol(productNameEn, 1, 'bushel');
	}
	
	cpt = 0;
	$('.ProductActiveContracts').each(function()
	{
		tmpTableCopy = ContractTables[cpt].clone(true);
		tmpTableCopy.find('td.num').each(function()
		{
			tmpTextVal = $(this).text();
			if(!isNaN(tmpTextVal) && tmpTextVal != '')
			{
				tmpVal = parseFloat(tmpTextVal) * volumeRate * currencyRate;
				$(this).text(numberFormatThousands(tmpVal.toFixed(nbDecimals)));
			}
		});
		$(this).replaceWith(tmpTableCopy);
		cpt++;
	});
	
	
	
	
	//Binds tooltip
	cpt=0;
	$('.ProductActiveContracts th[title]').each(function(){
		if(cpt == 0 || cpt == 1)
		{
			tmpTarget = 'topLeft';
			tmpToolTip = 'bottomLeft';
		}
		else
		{
			tmpTarget = 'topMiddle';
			tmpToolTip = 'bottomMiddle';
		}
		$(this).qtip({
			style : {name: 'dark', tip : tmpToolTip},
			position: {
		      corner: {
		         target: tmpTarget,
		         tooltip: tmpToolTip
		      }
		    },
			content : $(this).attr('title')
		
		});
		cpt++;
		$(this).removeAttr('title')
	});
}
/*
@author:jp
@desc:select row link
*/
function ProductActiveContractsClick()
{
	elem = $(this).find('a:first')
	if(elem.length)
	{
		location.href = elem.attr('href')
	}	
}
function productNameChange()
{
	val = $(this).val();
	//Update values for avaible base
	if(val == 'wheat' || val == 'oats' || val == 'soybean-meal')
	{
		disableBase();
		$('.UnavaibleBaseMessage').show();
	}
	else
	{
		if($('#ChartCurrency').val() == 'usd')	enableBase();
		$('.UnavaibleBaseMessage').hide();
	}
	
	//Update avalaible months for contracts
	
	var valueTmp = $('#ChartMonth').val();
	$('#ChartMonth option').remove();
	var select = document.getElementById('ChartMonth')
	if(select)
	{		
		for(index in productsFutureMonth[val]) 
		{
			select.options[select.options.length] = new Option(productsFutureMonth[val][index],index)
			
		}
	}
	$('#ChartMonth').val(valueTmp);
	
}
function updateTimeUnit() {
	$('#ChartTimeUnit option').removeAttr('disabled')
	var currentValue = $(this).val();
	var oldVal = $('#ChartTimeUnit').val();
	switch(currentValue) {
		case '1d':
			$('#ChartTimeUnit option[value="day"]').attr('disabled','disabled');
			$('#ChartTimeUnit option[value="week"]').attr('disabled','disabled');
			$('#ChartTimeUnit option[value="month"]').attr('disabled','disabled');
			$('#ChartTimeUnit option[value="year"]').attr('disabled','disabled');
			$('#ChartTimeUnit option[value="day"]').attr('disabled','disabled');
			$('#ChartTimeUnit option[value="15min"]').attr('selected','selected');
		break;
		
		case '1w':
			$('#ChartTimeUnit option[value="month"]').attr('disabled','disabled');
			$('#ChartTimeUnit option[value="year"]').attr('disabled','disabled');
			$('#ChartTimeUnit option[value="week"]').attr('disabled','disabled');
			$('#ChartTimeUnit option[value="15min"]').attr('selected','selected');
		break;
		
		case '1m' :
			$('#ChartTimeUnit option[value="month"]').attr('disabled','disabled');
			$('#ChartTimeUnit option[value="15min"]').attr('disabled','disabled');
			$('#ChartTimeUnit option[value="30min"]').attr('disabled','disabled');
			$('#ChartTimeUnit option[value="year"]').attr('disabled','disabled');
			$('#ChartTimeUnit option[value="hour"]').attr('selected','selected');
		break;
		
		case '3m' : case '6m' :
			$('#ChartTimeUnit option[value="15min"]').attr('disabled','disabled');
			$('#ChartTimeUnit option[value="30min"]').attr('disabled','disabled');
			$('#ChartTimeUnit option[value="hour"]').attr('disabled','disabled');
			$('#ChartTimeUnit option[value="year"]').attr('disabled','disabled');
			$('#ChartTimeUnit option[value="day"]').attr('selected','selected');
		break;
		
		case '1y' :
			$('#ChartTimeUnit option[value="15min"]').attr('disabled','disabled');
			$('#ChartTimeUnit option[value="30min"]').attr('disabled','disabled');
			$('#ChartTimeUnit option[value="hour"]').attr('disabled','disabled');
			$('#ChartTimeUnit option[value="year"]').attr('disabled','disabled');
			$('#ChartTimeUnit option[value="week"]').attr('selected','selected');
		break;
		
		case '3y': case '5y' : case '10y' :
			$('#ChartTimeUnit option[value="15min"]').attr('disabled','disabled');
			$('#ChartTimeUnit option[value="30min"]').attr('disabled','disabled');
			$('#ChartTimeUnit option[value="hour"]').attr('disabled','disabled');
			$('#ChartTimeUnit option[value="day"]').attr('disabled','disabled');
			$('#ChartTimeUnit option[value="week"]').attr('selected','disabled');
			$('#ChartTimeUnit option[value="month"]').attr('selected','selected');
		break;
		
		case 'max':
			$('#ChartTimeUnit option[value="15min"]').attr('disabled','disabled');
			$('#ChartTimeUnit option[value="30min"]').attr('disabled','disabled');
			$('#ChartTimeUnit option[value="hour"]').attr('disabled','disabled');
			$('#ChartTimeUnit option[value="day"]').attr('disabled','disabled');
			$('#ChartTimeUnit option[value="week"]').attr('disabled','disabled');
			$('#ChartTimeUnit option[value="month"]').attr('selected','selected');
		break;
	}
	if(!$('#ChartTimeUnit option[value="'+oldVal+'"]').attr('disabled'))
	{
		$('#ChartTimeUnit').val(oldVal);
	}
	$('#ChartTimeUnit').trigger('change');
}

function updateChartType(){

}

function handleBaseClick() {
	var divParent = $('#advancedOptions div.checkDiv:visible');
	if($(divParent).find('input[type="checkbox"]:checked').length) {
		$('#ChartCurrency option[value="usd"]').attr('selected','selected');
		$('#ChartCurrency, #ch-currency label').attr('disabled','disabled').css('color','#aaa');
		$('#currencyMessage').slideUp();
	}
	else {
		allowCurrency();
	}
}

function allowCurrency() {
	$('#ChartCurrency, #ch-currency label').removeAttr('disabled').removeAttr('style');
}

function currencyChange() {
	var currentValue = $('#ChartCurrency').val();
	if(currentValue == 'cad') {
		$('#currencyMessage').css('visibility','visible');
		$('#currencyMessage').html('Les donn&eacute;es en dollars canadiens sont disponibles &agrave; partir de 1999 seulement.')
	}
	else if(currentValue == 'eur') {
		$('#currencyMessage').css('visibility','visible');
		$('#currencyMessage').html('Les donn&eacute;es en euros sont disponibles &agrave; partir de 1999 seulement.')
	}
	else {
		$('#currencyMessage').css('visibility','hidden');
	}
	//Disable base for not CAD
	if(currentValue != 'usd'){
		$('.UnavaibleBaseMessageCurrency').show();
		disableBase();
	}
	else{
		$('.UnavaibleBaseMessageCurrency').hide();
		tmpProductName = $('#ChartProductName').val();
		if(tmpProductName == 'corn' || tmpProductName == 'soybean') enableBase();
	}
	if($(this).attr('id')) 
	{	
    	anTrack1('Graphique', 'Devise', currentValue)
	}
}

function changeTab() {
	if($(this).attr('class')!='active') {
		$("#Charts ul.chartTabs li").removeClass("active"); //Remove any "active" class
		$(this).addClass("active"); //Add "active" class to selected tab
		$("#Charts .tab_content").hide(); //Hide all tab content
	
		var activeTab = $(this).find("a").attr("href"); //Find the href attribute value to identify the active tab + content
		$(activeTab).fadeIn(); //Fade in the active ID content
	}
	return false;
}

function checkActiveTab() 
{
	// Selected datatype when refreshing
	if($('#ChartsDatatype').val()=='contract')
	{
		$("#Charts ul.chartTabs li#secondTab").trigger('click');
	}
	else
	{
		$("#Charts ul.chartTabs li#firstTab").trigger('click');	
	}
}
function ChartUpdate() 
{
	$('#ChartFlash').hide()

	$('#ChartFlashWrap').css('background-image', 'none');
	$('#Chart').css('background-image', LoaderUrl);
		
	setInputDisabled($currencyInput);
	setInputDisabled($volumeInput);
	setInputDisabled($lengthInput);
	setInputDisabled($timeInput);
	setInputDisabled($typeInput);
	ChartParams.currency = $currencyInput.val();
	ChartParams.volumeUnit = $volumeInput.val();
	ChartParams.period = $lengthInput.val();
	ChartParams.timeUnit = $timeInput.val();
	ChartParams.type = $typeInput.val();
	
	var url = "/charts/index/";
	for(named in ChartParams)
	{
		url+= named+':'+ChartParams[named]+'/';
	}
	jQuery.get( url, {}, ChartUpdateCallBack, 'json');
	if($(this).attr('id') == 'ChartVolumeUnit') 
	{	
		anTrack1('Graphique', 'Volume', $volumeInput.val())
	}
   $('#SendLink').attr('href', '/contact/email/type:graph/url:'+Base64.encode(url));
   return false;
}
function ChartUpdateCallBack(data)
{
	resetInputDisabledState($currencyInput)
	resetInputDisabledState($volumeInput)
	resetInputDisabledState($lengthInput)
	resetInputDisabledState($timeInput);
	resetInputDisabledState($typeInput);
	$('#ChartFlash').show();
	$('#Chart').css('background-image', 'none');

    ofchartData = data;
	swfobject.embedSWF("/flash/open-flash-chart-2.swf", "ofchart", "714", "424", "9.0.9", "/flash/expressInstall.swf",false,{"wmode" : "transparent"});
    //load_1(ofchartData);
}
function enableBase(){
	$('#base, #prix').removeAttr('disabled');
	$('label[for="base"],label[for="prix"]').removeAttr('style')
}

function disableBase(){
	$('#base, #prix').attr('disabled','disabled');
	$('#base, #prix').removeAttr('checked' );
	$('label[for="base"],label[for="prix"]').css('color','#aaa')	
}
