 # but in theory could be used to call any `window.jQuery.fn` function
 Aui.modules = (jQuery?.site?.settings?.modules or []).slice()
 
+## internal cache of options passed to modules.
+moduleCache = {}
 ## internal class <Aui.Module/>
 # This class provides support for `Aui.modules` and handles calling jQuery.fn[module] calls
 Aui.Module = React.createClass

unless jQuery? then console.warn "Aui: window.jQuery not found, Modules and Semantic-UI will be disabled."
unless jQuery?.site?.settings?.modules? then console.warn 'Aui: No Semantic-UI window.jQuery.site.settings.modules found, Semantic will be disabled.'

## mixin AuiMixin
# !EXPIRIMENTAL
# Automatically wraps your render function with an <Aui>tag</Aui> with default props
AuiMixin =
  componentWillMount: ->
    render = @render
    @render = ->
      console.log 'Aui.Mixin'
      element = Aui.classify (render?.apply? @, arguments), @props
      unless React.isValidElement element
        console.error 'Aui: Child is not a valid Element:', element
        return React.DOM.span null, element
      element

## class <Aui/>
# Aui class is the main wrapper class
# it recursively goes through all it's children,
# finding props that === true or are on the `Aui.modules` list,
# and merges them into the className of each element.
Aui = React.createClass
  mixins: [AuiMixin]
  render: -> @props.children
Aui.Aui = Aui
Aui.Mixin = Aui.AuiMixin = AuiMixin

## object Aui.defaults
# The default options Aui uses when no options or props are passed in.

  componentDidMount: -> @callModules @props.children.props
  componentWillReceiveProps: (props) -> @callModules props.children.props
  callModules: (props) ->
    $element = jQuery React.findDOMNode @
    moduleId = $element.attr 'data-reactid'
    if moduleId isnt @moduleId
      console.log 'moduleId isnt @moduleId', moduleId, @moduleId
      delete moduleCache[@moduleId]
    @moduleId = moduleId
    moduleCache[@moduleId] or= {}
    for module, options in @props.modules
      cacheOptions = JSON.stringify options
      if moduleCache[@moduleId][module] isnt cacheOptions
        moduleCache[@moduleId][module] = cacheOptions
        ($element)[module] @props.children.props[module]...
    return
  componentWillUnmount: ->
    delete moduleCache[@moduleId]
window?.Aui = Aui
module?.exports = Aui
