/**
 * jQuery plugin checkboxes.
 * 
 * @author Jan Palko
 */
$.fn.checkBoxes = function() {
	return this.each(function() {
		var obj = $(this);
		
		obj.find('.jCheckRow').click(function(event) {
		    if (!$(event.target).is('input:checkbox')) {
    			if ($(this).hasClass('marked')) {
    				$(this).removeClass('marked').find('.jCheckBox:checkbox').removeAttr('checked');
    				obj.find('.jCheckAll:checkbox').removeAttr('checked');
    			}
    			else {
    				$(this).addClass('marked').find('.jCheckBox:checkbox').attr('checked', 'checked');
    				if (obj.find('.jCheckRow').length == obj.find('.jCheckRow.marked').length) {
    					obj.find('.jCheckAll:checkbox').attr('checked', 'checked');
    				}
    			}
		    }
		});
		
		obj.find('.jCheckRow .jCheckDisable').click(function() {
			$(this).closest('.jCheckRow').click();
		});
		
		obj.find('.jCheckCell').click(function() {
			if ($(this).hasClass('marked')) {
				$(this).removeClass('marked').find('.jCheckBox:checkbox').removeAttr('checked');
				obj.find('.jCheckAll:checkbox').removeAttr('checked');
			}
			else {
				$(this).addClass('marked').find('.jCheckBox:checkbox').attr('checked', 'checked');
				if (obj.find('.jCheckCell').length == obj.find('.jCheckCell.marked').length) {
					obj.find('.jCheckAll:checkbox').attr('checked', 'checked');
				}
			}
		});
		
		obj.find('.jCheckBox:checkbox').change(function() {
			if ($(this).is(':checked')) {
				$(this).closest('.jCheckRow,.jCheckCell').addClass('marked');
				if (obj.find('.jCheckRow').length > 0 && obj.find('.jCheckRow').length == obj.find('.jCheckRow.marked').length
						|| obj.find('.jCheckCell').length > 0 && obj.find('.jCheckCell').length == obj.find('.jCheckCell.marked').length) {
					obj.find('.jCheckAll:checkbox').attr('checked', 'checked');
				}
			}
			else {
				$(this).closest('.jCheckRow,.jCheckCell').removeClass('marked');
				obj.find('.jCheckAll:checkbox').removeAttr('checked');
			}
		});

		obj.find('.jCheckAll:checkbox').click(function() {
			if ($(this).is(':checked')) {
				obj.find('.jCheckRow,.jCheckCell').addClass('marked').find('.jCheckBox:checkbox').attr('checked', 'checked');
			}
			else {
				obj.find('.jCheckRow,.jCheckCell').removeClass('marked').find('.jCheckBox:checkbox').removeAttr('checked');
			}
		});
	});
};
