var MONTHS_JA = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];



var aafTimeline,monthTimeline;
function onLoad(){
    var eventSource = new Timeline.DefaultEventSource();
    
    /* 開催期間 */
    var zones = {
        '2009': {
            start: "Sat Jun 20 2009 00:00:00 GMT+0900",
            end: "Sun Sep 13 2009 00:00:00 GMT+0900"
        },
        '2010': {
            start: "Sat Jun 19 2010 00:00:00 GMT+0900",
            end: "Sun Tue 12 2010 00:00:00 GMT+0900"
        }
    }
    
    /*イベント表示エリアテーマ*/
    var theme = Timeline.ClassicTheme.create();
    
    theme.event.bubble.width = 397;
    
    theme.event.tape.height = 5;
    
    theme.event.label.offsetFromLine = 5;
    
    theme.event.track.offset = 40;
    theme.event.track.gap = 10;
    
    theme.event.instant.impreciseIconMargin = 40;
    
    theme.event.highlightLabelBackground = true;
    
    theme.ether.backgroundColors = '#fb0000'
    theme.ether.interval.line.show = true;
    theme.ether.interval.marker.hAlign = 'Top';
    
    /*月表示エリアテーマ*/
    var theme2 = Timeline.ClassicTheme.create();
    
    theme2.ether.backgroundColors = '#000';
    theme2.ether.interval.marker.hAlign = 'bottom';
    theme2.ether.interval.line.show = false;
    

    var today = new Date();
    
    /* テーマを適用 */
    var bandInfos = [Timeline.createBandInfo({
        width: "1040",
        intervalUnit: Timeline.DateTime.DAY,
        intervalPixels: 28,
        eventSource: eventSource,
        date: today,
         timeZone: +9,
     showEventText:  false,
        theme: theme,
        zoomIndex: 1,
        zoomSteps: new Array({
            pixelsPerInterval: 100,
            unit: Timeline.DateTime.DAY
        }, {
            pixelsPerInterval: 28,
            unit: Timeline.DateTime.DAY
        })
    })];
    
        var monthBandInfos = [Timeline.createBandInfo({
     width:          "50",
     intervalUnit:   Timeline.DateTime.DAY,
     intervalPixels: 28,
     date:           today,
        timeZone: -1,
     showEventText:  false,
     zoomIndex:      1,
     zoomSteps:      new Array(
     {pixelsPerInterval: 100,  unit: Timeline.DateTime.DAY},
     {pixelsPerInterval: 28,  unit: Timeline.DateTime.DAY})
     }),
     Timeline.createBandInfo({
     width:          "20",
     intervalUnit:   Timeline.DateTime.DAY,
     intervalPixels: 28,
     date:           today,
        timeZone: +9,
     zoomIndex:      1,
     zoomSteps:      new Array(
     {pixelsPerInterval: 100,  unit: Timeline.DateTime.DAY},
     {pixelsPerInterval: 28,  unit: Timeline.DateTime.DAY})
     })];
    
    monthBandInfos[0].etherPainter = new Timeline.GregorianEtherPainter({
     unit:   Timeline.DateTime.MONTH,
     multiple:   1,
     theme:      theme2
     });
     
     monthBandInfos[0].syncWith = 1;

    
    /* イベントエリア適用 */
    $.each(zones, function(i, item){
        bandInfos[0].decorators = [new Timeline.SpanHighlightDecorator({
            startDate: item.start,
            endDate: item.end,
            color: "#b0e0e6",
            opacity: 40,
            startLabel: "アートツーリズムでいこう<br />アサヒ・アート・フェスティバル 2009開幕",
            endLabel: "閉幕　　　",
            cssClass: 't-highlight1'
        })];
        monthBandInfos[1].decorators = [new Timeline.SpanHighlightDecorator({
            startDate: item.start,
            endDate: item.end,
            color: "#b0e0e6",
            opacity: 40,
            cssClass: 't-highlight1'
        })];
    })
    
    /*timeline生成 XML読み込み*/
    aafTimeline = Timeline.create(document.getElementById("calendar"), bandInfos, Timeline.HORIZONTAL);
    aafTimeline.loadXML("xml/calendar.xml", function(xml, url){
        eventSource.loadXML(xml, url);
        $('.timeline-event-bubble-body a').click(function(e){
            e.stopPropagation();
        })
        $('.timeline-event-icon').next().css({
            'padding-left': '5px'
        })
        $('#calendar').scrollTop(0);
        $('#calYear').html('<span>' + MONTHS_JA[aafTimeline._bands[0].getMinVisibleDate().getMonth()] + '</span> ' + aafTimeline._bands[0].getMinVisibleDate().getFullYear())
    });
    
    monthTimeline = Timeline.create(document.getElementById("calendar-header"), monthBandInfos, Timeline.HORIZONTAL);
    
    var permaDate = location.href.split('#')
    
        if (permaDate[1]) {
            var tmpDate = permaDate[1].split('_')
            
            
            if (tmpDate[0] > 0 && tmpDate[0] < 32 && tmpDate[1] >= 0 && tmpDate[1] < 12 && tmpDate[2] > 2008 && tmpDate[2] < 2020) {
                var perseDate = new Date(tmpDate[2], tmpDate[1], tmpDate[0]);
                
                
                aafTimeline.getBand(0).setMinVisibleDate(perseDate);
                monthTimeline.getBand(0).setMinVisibleDate(perseDate);
                
            }
            else {
                today.setHours(0)
                today.setMinutes(0)
                
                aafTimeline.getBand(0).setMinVisibleDate(today);
                monthTimeline.getBand(0).setMinVisibleDate(today);
            }
        }else {
                today.setHours(0)
                today.setMinutes(0)
                
                aafTimeline.getBand(0).setMinVisibleDate(today);
                monthTimeline.getBand(0).setMinVisibleDate(today);
            }
        
    aafTimeline._bands[0].addOnScrollListener(setOuterDisplayMonth)
    
    monthTimeline._bands[0].addOnScrollListener(setOuterDisplayMonth2)
    

    
    var currentTime = new Date();
    
    function setOuterDisplayMonth(){
        currentTime = aafTimeline._bands[0].getMinVisibleDate();
        $('#calYear').html('<span>' + MONTHS_JA[currentTime.getMonth()] + '</span> ' + currentTime.getFullYear())
        
        aafTimeline.getBand(0).setMinVisibleDate(currentTime)
        monthTimeline.getBand(0).setMinVisibleDate(currentTime)
    }
    
    function setOuterDisplayMonth2(){
        currentTime = monthTimeline._bands[0].getMinVisibleDate();
        $('#calYear').html('<span>' + MONTHS_JA[currentTime.getMonth()] + '</span> ' + currentTime.getFullYear())
        
        aafTimeline.getBand(0).setMinVisibleDate(currentTime)
        monthTimeline.getBand(0).setMinVisibleDate(currentTime)
    }
    
    /*年度ボタン*/
    $('#festerm a').click(function(e){
        e.preventDefault();
        aafTimeline.getBand(0).setCenterVisibleDate(new Date(zones[$(this).text()].start))
        monthTimeline.getBand(0).setCenterVisibleDate(new Date(zones[$(this).text()].start))
    })
    
    
    /*zoomボタン実装*/
    $('#zoomIn').click(function(e){
        e.preventDefault();
        
        $(this).addClass('selected')
        $('#zoomOut').removeClass('selected')
        
        var innerFrame = $('#timeline-band-0')[0];
        var loc = SimileAjax.DOM.getEventRelativeCoordinates(e, innerFrame);
        
        aafTimeline._bands[0]._timeline.zoom(true, -1 * $(innerFrame).css('left'), loc.y, innerFrame);
        monthTimeline.getBand(0)._timeline.zoom(true, -1 * $(innerFrame).css('left'), loc.y, innerFrame);
        
        var innerFrame2 = $('#timeline-band-1')[0];
        var loc2 = SimileAjax.DOM.getEventRelativeCoordinates(e, innerFrame2);
        
        monthTimeline.getBand(1)._timeline.zoom(true, -1 * $(innerFrame2).css('left'), loc2.y, innerFrame2);
        
        
        $('.timeline-event-icon').next().css({
            'padding-left': '5px'
        })
    })
    
    
    $('#zoomOut').click(function(e){
        e.preventDefault();
        $(this).addClass('selected')
        $('#zoomIn').removeClass('selected')
        
        var innerFrame = $('#timeline-band-0')[0];
        var loc = SimileAjax.DOM.getEventRelativeCoordinates(e, innerFrame);
        
        aafTimeline._bands[0]._timeline.zoom(false, -1 * $(innerFrame).css('left'), loc.y, innerFrame);
        monthTimeline._bands[0]._timeline.zoom(false, -1 * $(innerFrame).css('left'), loc.y, innerFrame);
        
        
        var innerFrame2 = $('#timeline-band-1')[0];
        var loc2 = SimileAjax.DOM.getEventRelativeCoordinates(e, innerFrame2);
        
        monthTimeline._bands[1]._timeline.zoom(false, -1 * $(innerFrame2).css('left'), loc2.y, innerFrame2);
        
        $('.timeline-event-icon').next().css({
            'padding-left': '5px'
        })
    })
}

$(function(){
    var knobHeight = 471*(450/1940);
    var knobMargin = $('#slider').height() - knobHeight;
    
    $('#knob').height(knobHeight)
    
    var first_point = null;
    
    $('#knob').bind('mousedown',function(e){
		e.preventDefault();
		first_point = e.pageY - $('#knob').offset().top;
		$('body').bind('mousemove',moveSlide)
        
	})
    
    
	$('body').bind('mouseup',function(e){
        if (first_point) {
            $('body').unbind('mousemove', moveSlide)
            first_point=null;
        }
	})
    
    function moveSlide(e){
		var slidePos = e.pageY - $('#slider').offset().top - first_point;
		
		
		if (slidePos >= 0 && slidePos <= knobMargin) {
            var containerPos = slidePos * (1940 - 450)/471
            $('#calendar').scrollTop(containerPos);
            $('#knob').css({
                'top': slidePos + 'px'
            })
        }
        else 
            if (slidePos < 0) {
                $('#knob').css({
                    'top': '0px'
                })
                $('#calendar').scrollTop(0);
            }
            else 
                if (slidePos > knobMargin) {
                    $('#knob').css({
                        'top': knobMargin + 'px'
                    })
                $('#calendar').scrollTop(1940 - 450);
                }
	}
    
})


var resizeTimerID = null;
function onResize(){
    if (resizeTimerID == null) {
        resizeTimerID = window.setTimeout(function(){
            resizeTimerID = null;
            aafTimeline.layout();
        }, 500);
    }
}




