function get_hash(href) {
    var ext = href.lastIndexOf('.') ;
    if ( ext == -1 ) {
        return href.substring(1) ;
    } else {
        return href.substring(1, ext) ;
    }
}

if ( location && location.pathname != '/' ) {
    location.replace('/#' + get_hash(location.pathname)) ;
}

$(function () {
    
    var initialized = false ;
    
    function set_active_link(hash) {
        $('a').removeClass('active') ;
        if ( hash.indexOf('/') != hash.lastIndexOf('/') ) {
            $('a[href=/' + hash.substring(0, hash.lastIndexOf('/')) + '.html]').addClass('active') ;
        } else {
            $('a[href=/' + hash + '.html]').addClass('active') ;
        }
    }
    
    function load(hash) {
        if ( ! hash ) {
            if ( initialized ) {
                hash = 'index' ;
            } else {
                return ;
            }
        }
        $('#page').fadeOut("fast", function () {
            $('#contents').addClass('hidden-page') ;
            $('#contents').load('/data/' + hash + '.html', function () {
                set_active_link(hash) ;
                $('#page').fadeIn("slow") ;
            }) ;
        }) ;
    }
    
    function load_ref(hash) {
        $('#ref-infos').fadeOut("fast", function () {
            $('#ref-infos').load('/reference/' + hash + '.html', function () {
                set_active_link(hash) ;
                $('#ref-infos').fadeIn("slow") ;
            }) ;
        }) ;
    }
    
    $.history.init(load);
    
    initialized = true ;
    
    $("a[href^=/]").livequery('click', function (e) {
        e.preventDefault() ;
        $(this).blur() ;
        if ( $(this).is('.ref') ) {
            $.history._callback = load_ref ;
            $.history.load(get_hash($(this).attr('href')));
            $.history._callback = load ;
        } else {
            $.history.load(get_hash($(this).attr('href')));
        }
    }) ;
    
    $.fn.animate_arrow_start = function () {
        $this = $(this) ;
        window.animate_arrow_cycle = function (step) {
            step = step || 0 ;
            $this.css('background-position', '0 -' + (21 + step) + 'px') ;
            step = (step + 21) % 63 ;
            setTimeout('window.animate_arrow_cycle && window.animate_arrow_cycle(' + step + ')', 300) ;
        }
        window.animate_arrow_cycle() ;
        
    }
    
    $.fn.animate_arrow_stop = function () {
        window.animate_arrow_cycle = null ;
        $(this).css('background-position', '0 0') ;
    }
    
    $('#menu > li').hover(
        function () {
            $('#page.home div#home-' + $(this).attr('class')).fadeIn(1) ;
            $('> a', this).animate_arrow_start() ;
        }, function () {
            $('#page.home div').fadeOut("slow") ;
            $('> a', this).animate_arrow_stop() ;          
        }
    ) ;
    
}) ;
