   displayName: 'ImageLoader'
   mixins: [LoaderMixin]
   propTypes:
+    wrapper: PropTypes.func
     preloader: PropTypes.func
     onLoad: PropTypes.func
     onError: PropTypes.func
-  getDefaultProps: -> preloader: img, loader: imageLoader
-  handleLoad: (el) -> @setState status: Status.LOADED
-  handleError: (error) -> @setState {error, status: Status.FAILED}
+  getDefaultProps: ->
+    wrapper: span
+  loadImage: (opts, cb) ->
+    @setState
+      status: Status.LOADING
+      imageToLoad:
+        opts: opts
+        cb: cb
+  handleLoad: (event) ->
+    img = @refs.img
+    if 'naturalWidth' of img and (img.naturalWidth + img.naturalHeight is 0) or (img.width + img.height is 0)
+      @handleError new Error "Image <#{img.src}> could not be loaded."
+    else
+      @setState status: Status.LOADED, =>
+        @props.onLoad()  # FIXME: What does this callback get?
+  handleError: (error) ->
+    @setState {error, status: Status.FAILED}, =>
+      @props.onError error
+  getClassName: ->
+    # Build a CSS class name based on the current state.
+    className = "imageloader #{ @state.status }"
+    className += " #{ @props.className }" if @props.className
+    className
   render: ->
+    (@props.wrapper
+      className: @getClassName()
+      @renderStatus()
+    )
+  renderStatus: ->
+    result = []
+    if @state.imageToLoad
+      result.push @renderImage()
     switch @state.status
-      when ImageLoader.Status.PENDING, ImageLoader.Status.LOADING
-        @props.preloader()
-      when ImageLoader.Status.ERROR
-        (div className: 'error', @props.children)
-      when ImageLoader.Status.LOADED
-        (img
-          src: @props.src
-          onLoad: @props.onLoad
-          onError: @props.onError
-        )
+      when Status.PENDING, Status.LOADING
+        result.push new @props.preloader if @props.preloader
+      when Status.ERROR
+        if Array.isArray @props.children
+          result = result.concat @props.children
+        else
+          result.push @props.children
+    result
+  renderImage: ->
+    (img
+      ref: 'img'
+      src: @state.imageToLoad.opts.url
+      onLoad: @handleLoad
+      onError: @handleError
+      style:
+        display: if @state.status is Status.LOADED then null else 'none'
+    )

LoaderMixin =
  statics: {Status}
  propTypes:
    loader: PropTypes.func.isRequired
    src: PropTypes.string.isRequired
    priority: PropTypes.number
  contextTypes:

React = require 'react'

{PropTypes} = React
{span, img} = React.DOM

Status =
  PENDING: 'pending'
