var Checkin = Class.create();

Checkin.prototype = 
{
	initialize: function( table, options )
	{
		this.table 			= table
		this.options 		= options || { prefix: 'checkin_'};
		
		Event.observe( window, 'load', this.addEvent.bindAsEventListener( this ) ); 
	},
	addEvent: function ( event )
	{
		$( this.table ).observe('click', this.check.bindAsEventListener( this ) );
	},
	check: function( object )
	{
		targetObject = object.target || object.srcElement;
		
		if ( targetObject.tagName == "BUTTON" )
		{
			var button = targetObject;
			var all = button.id.match( /^all_(\d+)$/ );
			var currentId = button.id.toArray();
		
			this.setClass( button );
			
			if ( all )
			{
				this.colCheck( all[1], button.className );
			}
			else
			{
				this.allButtonChecked( currentId[0] );
				this.checkAll( button );
				this.setHiddenElementValue( button );
			}
		}
	},
	colCheck: function( col, classname )
	{
		var buttons = document.getElementsByTagName("button");
		
		for ( var i = 0; i < buttons.length; i++ )
		{
			var checkId = buttons[i].id.toArray();
			
			if ( checkId[0] == col )
			{
				buttons[i].className = classname;
			
				this.setHiddenElementValue( buttons[i] );
			} 
		}		
	},
	setClass: function( button )
	{
		if ( button.className !=  "selected" )
		{
			button.className = "selected";
		}
		else
		{
			button.className = "";
		}	
	},
	setHiddenElementValue: function( button )
	{
		var hiddenField = $( this.options.prefix + button.id );
		if ( button.className == "selected")
		{
			if ( hiddenField )
			{
				hiddenField.value = 1;	
			}
		} 
		else if ( button.className != "selected" )
		{
			if ( hiddenField )
			{
				hiddenField.value = null;	
			}	
		}
	},
	checkAll: function ( button, allChecked )
	{
		if ( button != null )
		{
			var buttonid = button.id.toArray();
			var allChecked = allChecked | false;
			var all_button = $( 'all_' + buttonid[0] );
		
			if ( all_button != null )
			{
				if ( all_button.className == 'selected' && button.className != "selected" )
				{
					all_button.className = "";
				}
				else if ( all_button.className != "selected" && allChecked )
				{
					all_button.className = "selected";
				}
			}
		}
	},
	allButtonChecked: function ( id )
	{
		var allselected = true;
		
		for ( var i = 1; i < intervals; i++ )
		{
			if ( typeof( shifts ) != 'undefined' )
			{
				var button = $( id + '_' + shifts[i] );
			}
			else
			{
				var button = $( id + '_' + i );	
			}
			
			
			if ( button != null )
			{
				if ( button.className != "selected" )
				{
					allselected = false;
				}
			}
		}
		
		if ( allselected )
		{
			this.checkAll( button, true );
		}
	}
} 
