jQuery( document ).ready( function() {
	var config = {
		template: jQuery('#collectionTemplate3'),
		//	Initial data
		data: [
			{ id: 1, name: 'David Lann', customerType: 'v', order: '1' },
			{ id: 2, name: 'Jill Jones', customerType: 'n', spam: 'true', order: '2' }
		],
		addButton: jQuery('#addButton3'),
		deleteButtonName: 'deleteButton',
		beforeAdd: function( data, args ) {
			//	Set the order, using the collection count
			var collectionCount = parseInt( jQuery( args.addButton ).attr( 'collectionCount' ), 10 );
			data['order'] = data['order'] || collectionCount;
			return data;
		},
		bindings: {
			//	Move up collection, freezing the order field values
			'moveUpButton': {
				event: 'click',
				func: function( e, collection ) {
					jQuery.fn.moveUpCollection( collection, ['order'] );
				} 
			},
			//	Move down collection, freezing the order field values
			'moveDownButton': {
				event: 'click',
				func: function( e, collection ) {
					jQuery.fn.moveDownCollection( collection, ['order'] );
				} 
			}
		},
	    //      Override the delete function, to send ajax request if necessary
		deleteFunction: function( template, args, data, deleteButton ) {
		    jQuery( deleteButton ).text( 'Deleting...' ).attr( 'disabled', 'disabled' );
		    
		    //      If we have data, send it to the server to delete, otherwise simply remove
		    var dataLength = 0;
		    for( var x in data )dataLength++;
		    
		    if( dataLength > 0 ) {
				//      Add delete parameter to the data
				data['action'] = 'delete';
				
				var request = jQuery.ajax( {
					type: 'POST',
					data: data,
					url: 'collections.php',
					dataType: "text",
					error: function() {
						alert( "Ajax error occured" );
					},
					success: function( html ) { //      Remove collection
						jQuery.fn.removeCollection(template, args, data);
					}
				} );
		    } else {
				jQuery.fn.removeCollection( template, args, data );
			}
		},
		namePattern: "contact{number}[{name}]"
	};
	
	jQuery('#collectionTarget3').collections(config);
} );
