 {div, span, a, i} = React.DOM
+
+shuffle = (a) ->
+  idx = a.length
+  while --idx > 0
+    j = ~~(Math.random() * (idx + 1))
+    t = a[j]
+    a[j] = a[idx]
+    a[idx] = t
+  a
 
 window.MaterialsCollectionClass = React.createClass
   getInitialState: ->

    truncated: true

  componentDidMount: ->
    jQuery.ajax
      url: Portal.API_V1.MATERIALS_BIN_COLLECTIONS
      data: id: @props.collection
      dataType: 'json'
      success: (data) =>
        @setState materials: data[0].materials if @isMounted()

  toggle: (e) ->
    @setState truncated: not @state.truncated


window.MaterialsCollection = React.createFactory MaterialsCollectionClass

Portal.renderMaterialsCollection = (collectionId, selectorOrElement, limitOrOptions = Infinity) ->
  # Keep API backward compatible, so accept either 'limit' option as the last argument or hash.
  options = if typeof limitOrOptions == 'number'
              {limit: limitOrOptions}
            else
              limitOrOptions
  React.render MaterialsCollection(collection: collectionId, limit: options.limit, randomize: options.randomize),
    jQuery(selectorOrElement)[0]
