/* ------------------------------------------------------------
 * PROJECT        : 
 * FILENAME       : jq.toggleAllCheckboxes.js
 * ------------------------------------------------------------
 * LAST UPDATED   : 29 Oct 2009
 * ------------------------------------------------------------
 * AUTHOR(S)      : Kevin Scholl (ksscholl@magellanhealth.com/)
 * ------------------------------------------------------------ */

/*

SUMMARY

This plugin will select or deselect all checkboxes in a related group based on the status of one or more controls elements, typically a global checkbox.

OPTIONAL SETTINGS

(none)

USAGE

$("input:checkbox[rel='GRP']").toggleAllCheckboxes();

where GRP is the group of checkboxes associated by their REL attribute.

EXAMPLE

$(document).ready(function() {
	$("input:checkbox[rel='cbDetail']").toggleAllCheckboxes();
	});

MINIMUM BROWSER SUPPORT

Apple Safari 3, Google Chrome 1, Microsoft Internet Explorer 6, Mozilla Firefox 3, Opera 9

*/

jQuery.fn.toggleAllCheckboxes = function(settings) {
  this.click(function() {
											
    var thisGroup  = "input:checkbox[rel='" + $(this).attr("rel") + "']";
    var allChecked = true;
		
    // if an "ALL" checkbox is checked/unchecked, check/uncheck all individual checkboxes
    if ($(this).attr("value") == "All")
      $(thisGroup).attr("checked",$(this).attr("checked"));
			
    // if an individual checkbox is ...
    if ($(this).attr("checked") == false)
      // ...unchecked, uncheck "ALL" checkboxes
      $(thisGroup + "[id*='All']").attr("checked",false);
			
    else {
      // ...checked, see if all individual checkboxes are checked ...
      $(thisGroup + ":not([value='All'])").each(function (i) {
        if ($(this).attr("checked") == false) {
          allChecked = false;
          return false;
          }
        });
      // ...and if they are, check "ALL" checkboxes
      if (allChecked == true)
        $(thisGroup + "[id*='All']").attr("checked","checked");
      }
    });
  };
