var Module = new Class(
{

	/* properties */
	
	/* methods */
	initialize: function()
	{

		if( $E( '.ku-list' ) || $E( '.ku-tree' ) )
			this.init_list();

		else if( $E( '.ku-form' ) )
			this.init_form();

		else if( $E( '.ku-sort' ) )
			this.init_sort();
	},


	/* inits */
	init_form: function()
	{
		new kuval( $E( '.ku-form' ) );
	},

	init_list: function()
	{
		// create an event for each link
		$$( '.ku-list a.link-delete' ).each( function( oAnchor )
		{
			oAnchor.addEvent( 'click', this.handle_delete.create({ 'bind': oAnchor }) );
		}, this );
		
		$$( '.ku-tree a.link-delete' ).each( function( oAnchor )
		{
			oAnchor.addEvent( 'click', this.handle_delete.create({ 'bind': oAnchor }) );
		}, this );

		if( $E( 'input[name=check_all]' ) )
		{
			// add event to check all button
			var oCheckAll = $E( 'input[name=check_all]' );
			oCheckAll.addEvent( 'change', this.handle_checkall.create({ 'bind': oCheckAll }) );
	
			// add event to the submit link
			$E( 'a.submit_delete' ).addEvent( 'click', this.handle_delete_m.create({ 'bind': oCheckAll }) );
		}
	},

	init_sort: function()
	{
		new Sortables( $E( '.ku-sort' ),
		{
			/*snap: 0,*/
			onDragStart: function( oElement, oGhost )
			{
				oGhost.addClass( 'sort-ghost' );
				oGhost.setStyle( 'opacity', 0.7 );
				oElement.setStyle( 'opacity', 0 );
			},
			onComplete: this.handle_sort
		});
	},


	/* handlers */
	handle_checkall: function( e )
	{
		$( this.form ).getElements( 'input[type=checkbox]' ).setProperty( 'checked', this.getProperty( 'checked' ) );
	},

	handle_delete: function( e )
	{
		// pop up a confirm box to confirm delete
		var bDelete = confirm( 'Weet u zeker dat u dit item wilt verwijderen?' );

		// they're sure
		if( !bDelete )
			new Event( e ).stop();
	},

	handle_delete_m: function( e )
	{
		var bDelete = confirm( 'Weet u zeker dat u dit items wilt verwijderen?' );
		
		if( bDelete )
		{
			var oForm = $( this.form );
			oForm.submit();
		}
		new Event( e ).stop();
	},

	handle_sort: function()
	{
		// array to catch the order of the id's
		var aIds = [];

		// loop the li's in the list
		this.list.getElements( 'li' ).each( function( oElement )
		{
			aIds.push( oElement.getProperty( 'id' ).replace( /id_/, '' ) );
		});

		// get name f the module we're in
		var sModule = this.list.getProperty( 'id' ).replace( /sort_/, '' );

		// the url to which the call should be made
		var sUrl = window.location.pathname.replace( '/sort', '/order' );

		// the data (id's) which should be sent
		var sData = 'sort[]=';
		sData += aIds.join( '&sort[]=' );

		// make an ajax call to update the order in the database
		new Ajax( sUrl,
		{
			data: sData,
			onComplete: function( r )
			{
				
			}
		}).request();
	}

});

init_module = function()
{
	new Module();
};

window.addEvent( 'domready', init_module );