/* requires glow ; net, dom */
glow.onDomReady(function(){
    if ( glow.env.opera < 8 ) {
        return;
    }

    function get_calendar_focus(calendar_url){
        var page_url, date, m;
        page_url = glow.dom.get("p#ataglance a")[0].href;
        date = page_url.match(/(\/\d{4}\/\d{2})\/(\d{2})/);
        m = page_url.match(/(\/\d{4}\/\d{2})/);
        if( m && date[1] == m[1] ){
           return parseInt(date[2], 10)
        } else { 
            return null;
        }
    }

    function update_calendar_focus(root, day){
        var h, t, node, nodes, i;
        nodes = root.get("td");
        for (i = 0; i < nodes.length; i++) {
            node = glow.dom.get(nodes[i]);
            if (node.hasClass("last_month") || node.hasClass("next_month")) {
                continue;
            }
            else if (node.text() == day && node.hasClass("date")) {
                node.addClass("focus");
                break;
            }
        }
    }

    function attach() {
        var prev = glow.dom.get('a#prev_month');
        var next = glow.dom.get('a#next_month');
        if (prev) { glow.events.addListener(prev,'click',function(){ click_handler(prev); return false; }) }
        if (next) { glow.events.addListener(next,'click',function(){ click_handler(next); return false; }) }
    }
    
    function click_handler(node) {
        var url = node.attr('href') + '/calendar';
        url = url.replace(/(\/[0-9]{4}\/[0-9]{2})\/[0-9]{2}/, '$1');
        return fetch(url, node.attr('href'));
    }

    function fetch(url, fallback_url) {
        var load_status = glow.dom.get("table.calendar > caption").addClass("calendar_loading");
        glow.net.get(url,{
            onLoad:function(response) {
                var calendar, day, node;
                calendar = response.text();
                day = get_calendar_focus(url);
                if(day>0){
                    node = glow.dom.create("<div></div>").html(calendar);
                    update_calendar_focus(node, day);
                    calendar = node.html();
                }
                glow.dom.get('div#calendar_wrapper').html(calendar);
                attach();
                load_status.removeClass("calendar_loading");
            },
            onError: function(request) {
                window.location.href = fallback_url;
            }
        });
        return false;
    }

    attach();

});
