/*
 * Master
 * http://rayboyd.com/
 *
 * Copyright (c) 2009 Ray Boyd
 * Dual licensed under the MIT and GPL licenses.
 */

// Load jQuery
google.load('jquery', '1.3.1');

// Dom ready?
google.setOnLoadCallback(start);

// Start app
function start()
{
    // Variables
    var grand_total = Number(0);

    // Display items
    $('.help').hide();
    $('<div class=grand_total>Grand Total: <span>0</span></div>').appendTo('.left_column');

    // Hide/Show help
    $('.help_toggle').click(function(){
        $('.help').toggle();
        $(this).toggleText('Help?', 'Close');
        return false;
    });

    // Add an item to the list
    $('.addtask').click(function()
    {
        // Reset colours
        $('.err1').css('color','black');
        $('.err2').css('color','black');
        $('.err3').css('color','black');

        // Get the data
        var description = $.trim($('input[name=description]').val());
        var hours       = Number($.trim($('input[name=hours]').val()));
        var rate        = Number($.trim($('input[name=rate]').val()));

        // Validate, break program flow or add item to document
        if(!description)
        {
            $('.err1').css('color','red');
        }
        else if(!hours)
        {
            $('.err2').css('color','red');
        }
        else if(!rate)
        {
            $('.err3').css('color','red');
        }
        else
        {
            // Calculate total
            var total = hours * rate;

            // Format output
            var dd_description = '<td>' + description + '</td>';
            var dd_hours       = '<td>' + hours + '</td>';
            var dd_rate        = '<td>' + rate  + '</td>';
            var dd_total       = '<td>' + total + '</td>';
            var output         = dd_description + dd_hours + dd_rate + dd_total;

            // Insert output
            $('<tr class=result total=' + total + '></tr>').html(output).appendTo('table');
            setGrandTotal(total);
        };
        return false;
    });

    // Click the item to remove
    $('.result').live('click', function()
    {
        var n = Number($(this).attr('total'));
        setGrandTotal(n-n-n);
        $(this).die().remove();
        return false;
    });

    // Add visual hints to display list items
    // over
    $('.result').live('mouseover', function()
    {
        $(this).css({
            'cursor':'pointer',
            'background-color':'#f9f9f9'
        });
    });
    // out
    $('.result').live('mouseout', function()
    {
        $(this).css({
            'background-color':'white'
        });
    });

    function setGrandTotal(total)
    {
        grand_total = total + grand_total;
        $('.grand_total span').text(grand_total);
    };

    /**
     * Extend jQuery
     * toggleText
     */
    (function($){
      $.fn.extend({
        toggleText: function(on, off){
          this.text(this.text() === on ? off : on);
        }
      });
    })(jQuery);

};
