public function save()
    {
        // Get document type
        $type = $this->getType();

        // Ensure all requirements are checked, otherwise bail out with a
        // runtime exception.
        if ( $this->checkRequirements() !== true )
        {
            throw new phpillowRuntimeException(
                'Requirements not checked before storing the document.'
            );
        }

        // Check if we need to store the stuff at all
        if ( ( $this->modified === false ) &&
             ( $this->newDocument !== true ) )
        {
            return false;
        }

        // Generate a new ID, if this is a new document, otherwise reuse the
        // existing document ID.
        if ( $this->newDocument === true )
        {
            $this->storage->_id = $this->getDocumentId( $type, $this->generateId() );
        }

        // Do not send an attachment array, if there aren't any attachments
        if ( !isset( $this->storage->_attachments ) ||
             !count( $this->storage->_attachments ) )
        {
            unset( $this->storage->_attachments );
        }

        // If the document ID is null, the server should autogenerate some ID,
        // but for this we need to use a different request method.
        $db = $this->getConnection();
        if ( $this->storage->_id === null )
        {
            // Store document in database
            unset( $this->storage->_id );
            $response = $db->post(
                $this->getDatabase(),
                json_encode( $this->storage )
            );
        }
        else
        {
            // Store document in database
            $response = $db->put(
                $this->getDatabase() . urlencode( $this->_id ),
                json_encode( $this->storage )
            );
        }

        $this->storage->_rev = $response->rev;

        // Restore the __attachments array if it has been removed before
        if ( !isset( $this->storage->_attachments ) ) 
        {
            $this->storage->_attachments = array();
        }
        
        // This document is no longer new
        $this->newDocument = false;
        
        return $this->storage->_id = $response->id;
    }