(function($) {
////
  $.fn.tally = function() {
    return this.each(function() {
      $(this).keyup(function() {
    	  var css = $(this).parent('td').attr('class'),
    	      total_css = '.' + css + '-total',
    	      row_css = '.' + css + ' input.text',
    	      row_total = 0;

        // totalize for row in question
        $(row_css).each(function() { row_total += Number($(this).val()); });
        // write the actual value
    	  $(total_css).html(row_total.toString())	  
    	})
    })
  }
  
////
  $.fn.handleToggle = function() {
    return this.each(function() {
      $(this).click(function() {
    	  var link = $(this), link_text = '',
    	      element = '#' + link.attr('class'),
    	      hide_link = link.html().indexOf('Show') == -1;

        link_text = hide_link ? 
          link.html().replace(/Hide/, 'Show') : 
            link.html().replace(/Show/, 'Hide')

    	  link.html(link_text);

    	  $(element).toggle();
    	  
    	  return false;
    	})
    })
  }
  
////
  $.fn.loadScorecard = function(options) {
    var settings = $.extend({
      dom_id: '#round-scorecard'
    }, options)
    
    $.extend({
      round: {
        saved_selection: null,
        modified: false,
        load: function(dropdown) {
          $(settings.dom_id).find('input.text').each(function() {
            if ($(this).val() != '') { $.round.modified = true; return }
          })
          
          if ($.round.modified) {
            if (confirm("Warning: your current changes will be lost! Continue?")) {
              $.round.swap(dropdown)
              $.round.modified = false
            } else $(dropdown).val($.round.saved_selection)
          } else { $.round.swap(dropdown) }
        },
        swap: function(selection) {
          $.get('/courses/' + Number(selection.value).toString() + '/rounds/new', function(data) {
            $('#round-scorecard').html(data).find('input.text').tally()
          })
        }
      }
    })
    
    return this.each(function() {
      $(this).click(function() { $.round.saved_selection = this.value }).change(function() { $.round.load(this) })
    })
  }
  
////
  $.fn.submitWithAjax = function() {
    this.submit(function() {
      $.post(this.action, $(this).serialize(), null, "script")
      return false
    })
    
    return this
  }

////
  $.fn.initGraph = function() {
    return this.each(function() {
      $(this).submit(function() {
        $('input.width').val($('#graph').width())
        $.post(this.action, $(this).serialize(), null, "script")
        return false
      })
    })
  }
})(jQuery);