var init_fc_tl = function() {

    $('#fc-tl-key div.link a').click(function(){
        var cl = $(this).attr('class');
        if (cl == 'today') today();
        else if (cl == 'start') start();
        else if (cl == 'end') end();
        return false;
    });

    $('#fc-tl-key select').change(function(e){
        go(Date.parse($(this).val()));
    });
    
    $('#fc-tl-key div.key-site').click(function(){
        $('#fc-tl-key div.sel').removeClass('sel');
        $(this).addClass('sel');
        var site = $(this).text();
        if (site != 'ALL') {
            tlLoad(site);
        } else {
            tlLoad();
        }
    });

    var tl = null;
    var tlDate = new Date();
    var tlBands = null;
    var tlBandUnits = [];
    var tlEventSource = new Timeline.DefaultEventSource();
    
    var tlTheme = Timeline.ClassicTheme.create();
    tlTheme.event.label.width   = 150;
    tlTheme.event.bubble.width  = 300;
    tlTheme.event.bubble.height = 200;
    
    tlTheme.event.duration.opacity         = 85;
    tlTheme.event.instant.impreciseOpacity = 30;
    
    tlTheme.event.track.offset  = 3; // em
    
    tlTheme.ether.interval.marker.hAlign = 'Top';
    tlTheme.ether.interval.marker.hTopStyler = function(elmt){
        elmt.className = 'time-label';
    };
    
    var tlThemeSummary = new Timeline.ClassicTheme.create();
    tlThemeSummary.event.instant.impreciseOpacity = 100;
    tlThemeSummary.ether.interval.marker.hBottomStyler = function(elmt){
        elmt.className = 'summary-time-label';
    };
    
    function tlLoad(site) {
        if (tl != null) {
            tlDate = tl.getBand(/*1*/0).getCenterVisibleDate();
            tl.dispose();
        }
        tl = Timeline.create($('#fc-tl')[0], tlGetBands(), Timeline.HORIZONTAL);
        go(tlDate);
        
        var url = "/campaigns/index.php?getfc";
        if (site) url += '=' + site;
        
        tl.loadJSON(url, function(json, url) {
            tlEventSource.loadJSON(json, url);
        });
    }
    
    function tlGetBands() {
        /* This needs to be re-created in order to clear the data from a previous load.
         * The data must be stored here then (haven't looked into it).
         */
        tlEventSource = new Timeline.DefaultEventSource();
        tlEventSource.addListener({
            onAddMany: function(){
                var d0 = tlEventSource.getEarliestDate().clone();
                var d1 = tlEventSource.getLatestDate().clone();

                d0 = d0.set({ month: 0, day: 1, hour: 0, minute: 0, second: 0 });
                d1.add(1).years();
                
                var html = '';
                
                var d = d0;
                while (d < d1) {
                    html += '<option value="' + d.toString('yyyy-mm-dd') + '">' + d.toString('yyyy') + '<\/option>';
                    d.add(1).years();
                }
                $('#fc-tl-key select').html(html);

                var sel = $('#fc-tl-key div.sel').text();
                var dec = [ ];
                if (sel == 'AMF') {
                    dec.push({ label: 'AMF 1 Availability', date: tlEventSource.getLatestDate().clone().add(8).weeks() });
                    dec.push({ label: 'AMF 2 Availability', date: Date.parse('Dec 1, 2013') });
                    
                } else if (sel == 'AAF') {
                    dec.push({ label: 'AAF Availability', date: Date.parse('Jan 1, 2013') });
                }
                for (var d=0; d<dec.length; d++) {
                    for (var i=0; i<tlBands.length; i++) {
                        var band = tl.getBand(i);
                    
                        var decorator = new Timeline.PointHighlightDecorator({
                            date: dec[d].date,
                            label: (i == 0) ? dec[d].label : '',
                            color: "#999999",
                            opacity: 50,
                            /* Doesn't seem to work.
                            cssClass: 'point-marker',
                            */
                            theme: tlTheme
                        });
                        decorator.initialize(band, tl);
                        decorator.paint();
                        
                        if (band._decorators) {
                            band._decorators.push(decorator);
                        } else {
                            band._decorators = [ decorator ];
                        }
                    }
                }
            }
        });
        
        tlBands = [
            Timeline.createBandInfo({
                eventSource: tlEventSource,
                width: '85%',
                trackGap: 0.3,
                intervalUnit: Timeline.DateTime.YEAR,
                intervalPixels: 400,
                theme: tlTheme
            }),
            Timeline.createBandInfo({
                eventSource: tlEventSource,
                trackHeight: 0.3,
                trackGap: 0.0,
                showEventText: false,
                width: '15%',
                intervalUnit: Timeline.DateTime.YEAR,
                intervalPixels: 100,
                theme: tlThemeSummary
            })
        ];
        tlBands[1].syncWith = 0;
        tlBands[1].highlight = true;
        tlBands[1].eventPainter.setLayout(tlBands[1].eventPainter.getLayout());
        
        for (var i=0; i<tlBands.length; i++) {
            tlBands[i].decorators = [
                new Timeline.PointHighlightDecorator({
                    date: new Date(),
                    color: "#000000",
                    opacity: 20
                })
            ];
        }
        
        return tlBands;
    }
    
    function go(date) {
        tl.getBand(/*1*/0).setCenterVisibleDate(date);
    }
    
    function today() { go(new Date()); }
    function start() { go(tlEventSource.getEarliestDate()); }
    function end()   { go(tlEventSource.getLatestDate()); }

    var resizeTimerID = null;
    $(window).resize(function(){
        if (resizeTimerID == null) {
            resizeTimerID = window.setTimeout(function(){
                resizeTimerID = null;
                if (tl != null) {
                    tl.layout();
                }
            }, 500);
        }
    });
    
    tlLoad();
};

