$(function () {
    $('#data').css({
        position: 'absolute',
        left: '-9999em',
        top: '-9999em'
    });
});

window.onload = function() {

    var commify = function(d) {
        d += '';
        var x = d.split('.');
        var x1 = x[0],
            x2 = x.length > 1 ? '.' + x[1] : '';
        var rgx = /(\d+)(\d{3})/;
        while (rgx.test(x1)) {
            x1 = x1.replace(rgx, '$1' + ',' + '$2');
        }
        return x1 + x2;
    };

    // Grab the data
    var labels = [],
        data   = [];

    $('#data tfoot th').each(function () {
        labels.push($(this).html());
    });

    $('#data tbody td').each(function () {
        data.push($(this).html());
    });

    // Draw
    var width        = 800,
        height       = 250,
        leftgutter   = 30,
        bottomgutter = 20,
        topgutter    = 20,
        colorhue     = .4,
        color        = 'hsb(' + [colorhue, 1, .25] + ')',
        r            = Raphael('holder', width, height),
        txt          = {font: '12px Fontin-Sans, Arial', fill: '#1b2b0e'},
        txt1         = {font: '10px Fontin-Sans, Arial', fill: '#1b2b0e'},
        txt2         = {font: '12px Fontin-Sans, Arial', fill: '#000'},
        X            = (width - leftgutter) / labels.length,
        max          = Math.max.apply(Math, data),
        Y            = (height - bottomgutter - topgutter) / max,
        blinded      = true;

    r.drawGrid( leftgutter + X * .5, topgutter, width - leftgutter - X, height - topgutter - bottomgutter, 10, 10, '#333' );

    var path             = r.path({stroke: color, 'stroke-width': 1, 'stroke-linejoin': 'round'}),
        bgp              = r.path({stroke: 'none', opacity: .3, fill: color}).moveTo(leftgutter + X * .5, height - bottomgutter),
        frame            = r.rect(10, 10, 100, 40, 5).attr({fill: '#b1b38b', stroke: '#1b2b0e', 'stroke-width': 2}).hide(),
        label            = [],
        is_label_visible = false,
        leave_timer,
        blanket          = r.set();

    label[0] = r.text(60, 10, '$24').attr(txt).hide();
    label[1] = r.text(60, 40, '').attr(txt1).attr({fill: color}).hide();

    for (var i = 0, ii = labels.length; i < ii; i++) {

        var y = Math.round( height - bottomgutter - Y * data[i] ),
            x = Math.round( leftgutter + X * (i + .5) );

        bgp[ i == 0 ? 'lineTo' : 'cplineTo' ](x, y, 10);
        path[ i == 0 ? 'moveTo' : 'cplineTo' ](x, y, 10);

        var dot = r.circle(x, y, 2).attr( { fill: color, stroke: color } );

        blanket.push( r.rect( leftgutter + X * i, 0, X, height - bottomgutter ).attr( { stroke: 'none', fill: '#fff', opacity: 0 } ) );

        var rect = blanket[blanket.length - 1];

        (function (x, y, data, lbl, dot) {

            var timer, i = 0;

            $(rect.node).hover(
                function () {

                    if ( blinded && x > 640 ) return;

                    clearTimeout(leave_timer);

                    var newcoord = { x: +x + 7.5, y: y - 0 };

                    if (newcoord.x + 100 > width) newcoord.x -= 114;

                    frame.show().animate({x: newcoord.x, y: newcoord.y}, 200 * is_label_visible);

                    label[0].attr({text: '$' + data }).show().animate({x: +newcoord.x + 50, y: +newcoord.y + 12}, 200 * is_label_visible);
                    label[1].attr({text: lbl}).show().animate({x: +newcoord.x + 50, y: +newcoord.y + 27}, 200 * is_label_visible);

                    dot.attr('r', 4);
                    is_label_visible = true;
                    r.safari();
                },
                function () {

                    dot.attr('r', 2);
                    r.safari();

                    leave_timer = setTimeout(function () {
                        frame.hide();
                        label[0].hide();
                        label[1].hide();
                        is_label_visible = false;
                        r.safari();
                    }, 1 );
                }
            );
        })( x, y, data[i], labels[i], dot );
    }

    var blinder = r.rect( 635, 0, 162, 250, 10 );
    blinder.attr( { fill: color, stroke: color, 'fill-opacity': 1, 'stroke-width': 2 } );
    blinder.toFront();

    bgp.lineTo( x, height - bottomgutter ).andClose();
    frame.toFront();
    label[0].toFront();
    label[1].toFront();
    blanket.toFront();

    $('#submit_button').click( function() {

        if ( !blinded ) {
            return $('#marketguesser_form').submit();
        }

        blinder.hide();
        blinded = false;

        var final_quote_value        = parseFloat( $('#final_quote').val().replace( /^\$/, '' ) );
        var last_visible_quote_value = parseFloat( $('#last_visible_quote_text').html().replace( /^\$/, '' ) );

        if ( isNaN( final_quote_value ) ) {
            final_quote_value = 0;
        }

        if ( isNaN( last_visible_quote_value ) ) {
            last_visible_quote_value = 0;
        }

        var quote_change = new String( final_quote_value - last_visible_quote_value );
        quote_change = ( quote_change < 0 ? '-$' : '+$' ) + quote_change.replace( /^-/, '' );
        quote_change = quote_change.replace( /\.(\d\d).*$/, '.$1' );

        $('#quote_change').append( $('<span></span>').html( quote_change ).css( {
            'color'       : quote_change.match(/^-/) ? '#fb0000' : '#00fb00',
            'font-weight' : 'bold',
            'margin-left' : '10px'
        } ) );

        $('#last_visible_quote_text').html( '$' + final_quote_value );

        var invested_credits = $('#invest_credits').val();

        if ( invested_credits > 0 ) {

            var user_credits = $('#user_credits').val();
            var start_credits = user_credits;

            user_credits -= invested_credits; // decrease by amount invested

            var number_shares_owned = invested_credits / last_visible_quote_value;
            var current_value       = number_shares_owned * final_quote_value;

            user_credits += current_value; // increase by the value of the stock

            var end_credits = user_credits;
            $('#user_credits').val(user_credits);

            user_credits = (new String(user_credits)).replace( /\.(\d\d).*$/, '.$1' );

            $('#user_credits_text').html( '$' + commify( user_credits ) );

            var change = end_credits - start_credits;
            change = ( change < 0 ? '-$' : '+$') + (new String(change)).replace(/^-/,'');
            change = (new String(change)).replace(/\.(\d\d).*$/, '.$1');

            $('#user_credits_text').parent().append( $('<span></span>').html( commify( change ) ).css( {
                'color'       : change.match(/^-/) ? '#fb0000' : '#00fb00',
                'font-weight' : 'bold',
                'margin-left' : '10px'
            } ) );
        }

        var company_name  = $('#company_name').val();
        var symbol        = $('#symbol').val();
        $('#investment_td').html( company_name + '&nbsp;(<a href="http://finance.yahoo.com/q?s=' + symbol + '" target="_Blank">' + symbol + '</a>)');
        $('#investment_td').css( { "textAlign": "center", "fontWeight": "bold" } );

        $(this).val('next >>');
    } );
};


