var ChartWidget = Class.create(
{
    initialize: function()
    {
        $('graph-panel').update('<div id="chart-flash"></div>');

        this.renderGraph();

		$('graph-controls-form').observe('submit', function(event){
			event.stop();

			this.renderGraph(this.getProductId(), $F('graph-start'), $F('graph-stop'));
			
		}.bind(this));
    },
	
	renderGraph: function(productId, start, stop)
	{
		if(!productId){ productId = this.getProductId(); }
		if(!start){ start = 0; }
		if(!stop){  stop  = 0; }
		
		swfobject.embedSWF(
            "http://" + window.location.hostname + "/scripts/lib/charts/MSLine.swf?XMLLoadingText=Chargement&ChartNoDataText=Aucune données...",
            "chart-flash",
            "100%",
            "420",
            "9.0.0",
            "http://" + window.location.hostname + "/scripts/lib/swfobject/expressInstall.swf",
            {
                chartWidth : '100%',
                chartHeight: 420,
                dataURL    : "http://" + window.location.hostname + '/products/' + productId + '-data/start/' + start + '/stop/' + stop
            },
            {
                movie        : "http://" + window.location.hostname + "/scripts/lib/charts/MSLine.swf?XMLLoadingText=Chargement&ChartNoDataText=Aucune données...",
                wmode        : 'transparent',
                swliveconnect: true,
                scale        : 'noscale',
                salign       : 'TL',
                bgcolor      : '#FFFFFF',
                wmode        : 'opaque',
                dataURL      : "http://" + window.location.hostname + '/products/' + productId + '-data/start/0/stop/0'

            }
        );
	},

    getProductId: function()
    {
        var parts = window.location.href.toLocaleLowerCase().split('/products/');

        if(0 < parts.length)
        {
            var productId = parts[1].split('-')[0];

            return productId;
        }

        return null;
    }
});

var MonthlyFilesWidget = Class.create(
{
    initialize: function()
	{
		var bg          = this.createBg();
		var toggle_btns = $$('a.file-pane-btn');

		this.redraw();

        toggle_btns.each(function(toggle_btn)
        {
    		toggle_btn.observe('click', function(event){
    			event.stop();

    			if(this.bg.visible())
    			{
    				this.hideForm();
    			}
    			else
    			{
    				this.loadFile(toggle_btn.id);
    			}
    		}.bind(this));
        }.bind(this));
	},

	toggleBackground: function()
	{
		if(this.bg.visible())
		{
			this.bg.fade({duration:.2});
		}
		else
		{
			this.bg.appear({duration: .2, from:0, to: .8});
		}
	},

	createBg: function()
	{
		this.bg = new Element('div', {id: 'ACOFI-monthly-file_bg'});

		$(document.body).insert({bottom: this.bg.hide()});

		this.bg.observe('window:resize', this.redraw.bind(this));
		this.bg.observe('click', this.hideForm.bind(this));

		return this.bg;
	},

	createPane: function(htmlContent)
	{
		this.pane    = new Element('div', {id: 'acofi-monthly-file_pane'});
		this.content = new Element('div', {id: 'acofi-monthly-file-content'});

        this.pane.setStyle({
            overflow  : 'auto',
            background: '#fff'
        });

        this.content.update(htmlContent);

		$(document.body).insert({bottom: this.pane.insert(this.content)});

		this.redraw();

		return this.content;
	},

	removePane: function()
	{
		this.pane.remove();
	},

	redraw: function()
	{
		var scr = document.viewport.getDimensions();

		this.bg.setStyle({position: 'fixed', zIndex: 10000, top: '0px', left: '0px', width: scr.width + 'px', height: scr.height + 'px', backgroundColor: '#000000', opacity: .8});
		if(this.pane)
		{
			this.pane.setStyle({position: 'fixed', zIndex: 10001, width: '980px', maxHeight: (scr.height-100) + 'px', left: ((scr.width-960)/2) + 'px', top: '50px'});
		}
	},

	loadFile: function(f_id)
	{
	   this.toggleBackground();

	   new Ajax.Request('/products/monthly-file/',
            {
                method    : 'post',
                parameters: 'f_id=' + f_id,
                onSuccess : function(transport){
                    this.createPane(transport.responseText);

                }.bind(this)
            });
	},

	hideForm: function()
	{
		this.removePane();
		this.toggleBackground();
	}
});

var PanesWidget = Class.create(
{
	initialize: function()
	{
		var tabs     = $$('.pw-tab');
		var panes    = $$('.pw-pane');
		var selected = 0;
		var updating = false;

		panes.each(function(p, i)
		{
			if(p.hasClassName('selected'))
			{
				selected = i;
			}
			else
			{
				p.hide();
			}

			new TableWidget($('data'+(i+1)), i+1);
		});

		tabs.each(function(t, i){
			t.observe('click', function(event)
			{
				event.stop();

//				if(Effect)
//				{
//					if(!updating && i!=selected)
//					{
//						new Effect.Fade
//						(
//							panes[selected],
//							{
//								from: 1,
//								to: 0,
//								duration: .28,
//								fps:60,
//								beforeStart: function()
//								{
//									updating = true;
//								},
//								afterFinish: function()
//								{
//									$(tabs[selected].parentNode).removeClassName('selected');
//									$(tabs[i].parentNode).addClassName('selected');
//
//									new Effect.Appear(
//										panes[i],
//										{
//											duration: .22,
//											fps:60,
//											afterFinish: function()
//											{
//												selected = i;
//												updating = false;
//											}
//										}
//									)
//								}
//							}
//						)
//					}
//				}
//				else
//				{
					panes[selected].hide();
					$(tabs[selected].parentNode).removeClassName('selected');

					panes[i].show();
					$(tabs[i].parentNode).addClassName('selected');

					selected = i;
//				}
			});
		});
	}
});

var TableWidget = Class.create(
{
	initialize: function(el, nb)
	{
		if(el==null) return;

		this.nb    = nb;
		this.lines = el.select('tr');
		this.years = $A();

		this.lines.each(function(l, i){
			if(l.hasClassName('year'))
			{
				this.years.push({offset: i, value: l.childElements()[0].innerHTML});
				l.hide();
			}
		}.bind(this));

		if(this.years.length>1)
		{
			this.createSelect();
		}
		else if(this.years.length==1)
		{
			$('date' + this.nb).insert(' ' + this.years[0].value);
		}
	},

	collapse: function(start, end)
	{
		for(cpt=start, len=end;cpt<len;cpt++)
		{
			this.lines[cpt].hide();
		}
	},

	createSelect: function()
	{
		var options = '';
		this.years.each(function(y, i){
			var year = y.value;
			options += '<option value="'+ year +'">' + year + '</option>';
		}.bind(this));

		$('date' + this.nb).insert('<select id="data-select' + this.nb + '">' + options + '</select>');

		var lb = $('data-select' + this.nb);
		var options = lb.options;

		lb.observe('change', function(){
			this.selectYear(options[options.selectedIndex].value);
		}.bind(this));

		this.selectYear(options[0].value);
	},

	selectYear: function(year)
	{
		var i     = 0;
		var start = 0;
		var stop  = 0;
		var end   = 0;

		for(cpt=0, len=this.years.length;cpt<len;cpt++)
		{
			if(this.years[cpt].value==year)
			{
				i     = cpt;
				start = this.years[cpt].offset + 1;
				break;
			}
		}

		if(i==this.years.length-1)
		{
			stop = this.lines.length;
		}
		else
		{
			stop = this.years[i+1].offset;
		}

		this.lines.invoke('hide');

		for(cpt=start ;cpt<stop;cpt++)
		{
			this.lines[cpt].show();
		}
	}
});

var PerfWidget = Class.create(
{
	initialize: function()
	{
		this.updateResults();

		$('formperf').observe('submit', function(event){
			event.stop();
			this.updateResults();
		}.bind(this));
	},

	format_date: function(date_fr)
	{
		var year  = date_fr.substring(6, 10);
		var month = date_fr.substring(3, 5);
		var day   = date_fr.substring(0, 2);

		return year + '-' + month + '-' + day;
	},

	updateResults: function()
	{
		var from  = this.format_date($F('from'));
		var until = this.format_date($F('until'));

		new Ajax.Request('/Products/performance/from/' + from + '/until/' + until + '/amount/' + $F('amount') + '/productID/' + $F('productID').stripTags().stripScripts(),
		{
			method: 'get',
			onSuccess: function(transport)
			{
				$('performance-result').innerHTML = transport.responseText;
			}
		});
	}
});

document.observe('dom:loaded', function(){
	new PanesWidget();
	new PerfWidget();
        new MonthlyFilesWidget();
        new ChartWidget();
});

