var GRAPH_CRIPPLED = false
$( document ).ready( function() {
    init_table()
    init_chooser()
    choose_graph_view( GRAPH_CRIPPLED ? 'plain' : 'graph' )
})

function init_table() {
    $( '.car-colors.graph td' ).hover(
        function() { car_colors_hover_over( $( this )) },
        function() { car_colors_hover_out() }
    )
    $( '.car-colors.graph th' ).hover(
        function() { car_colors_hover_over( $( this ), 'silver' ) },
        function() { car_colors_hover_out() }
    )
    /* this to show a useful message to browsers not supporting the table technique */
    var silver1 = $( '#graph table tbody tr:nth-child(1) .silver' )
    var silver2 = $( '#graph table tbody tr:nth-child(2) .silver' )
    if( silver1.width() == silver2.width() ) {
        $( '#graph' ).addClass( 'crippled' )
        $( '#graph' ).append( "<p class=\"old-browser\">I'm sorry, but you're using a crusty old web browser that doesn't support the technique I'm using.  Recent versions of all major browsers are supported.  If you can't upgrade, please enjoy the plain text table.</p>" )
        GRAPH_CRIPPLED = true
    }
}

function car_colors_hover_over( e, color ) {
    if( !color ) color = e.attr( 'class' )
    e.parent().addClass( 'highlight' )
    $( '.car-colors.graph td.'+color ).addClass( 'highlight' )
    $( '.car-colors.graph' ).addClass( 'dim' )
}

function car_colors_hover_out() {
    $( '.car-colors.graph' ).removeClass( 'dim' )
    $( '.car-colors.graph .highlight' ).removeClass( 'highlight' )
}

// chooser
function init_chooser() {
    $( '#chooser a' ).click(
        function() {
            var id = $( this ).parent().attr( 'id' ).match(/chooser-(\w+)/)[ 1 ]
            choose_graph_view( id )
            return false
        }
    )
    $( '#chooser a' ).hover(
        function() { $( '#graph' ).addClass( 'hover' )},
        function() { $( '#graph' ).removeClass( 'hover' )}
    )
}

function choose_graph_view( id ) {
    $( '#graph' )
        .removeClass( 'plain' )
        .removeClass( 'graph' )
        .addClass( id )
    $( '#chooser li' ).removeClass( 'active' )
    $( '#chooser-'+ id ).addClass( 'active' )
}

