 {Readable} = require 'stream'
 querystring = require 'querystring'
 
-# First char upper
-String::ucfirst = -> @charAt(0).toUpperCase() + @substr(1)
-
 # function -> script
 Function::script = (argv) ->
   env = ''

      throw new TypeError typeof(callback) + ' is not a function'
    @_error = callback

  # Sync client callback
  sync: -> @_sync = true

  # User event script
  script: (callback, argv) ->
    if typeof callback isnt 'function'
      throw new TypeError typeof(callback) + ' is not a function'
    @_callback += callback.script argv

  # Respond client
  _do: (req, @_buffer) ->

# Application script
application = ->
  # application object
  app = window.app = (event, selector) ->
    window.event = event
    app._url = "#{location.pathname}?selector=#{selector}&_id=event&_key="
    return app._selector[selector]() if typeof app._selector[selector] is 'function'
    # getting event script
    $.getScript app._url + 'script'
    .done -> app._selector[selector]() if typeof app._selector[selector] is 'function'

  # application events
  app._selector = {}
  app.selector = (selector) -> app _event, selector

  # core data
  app.core = {
    # base data carrier and catcher
    base: (model) ->
      # get value from dom element
      get = (elem, name) ->
        switch name.toString()
          when 'text' then value = elem.text()
          when 'html' then value = elem.html()
          when 'value' then value = elem.val()
          else value = elem.attr name
        return value
      # user data
      data = {}
      for id, attrs of model
        elem = $('#' + id)
        data[id] = {}
        unless $.isArray attrs then data[id] = get elem, attrs
        else data[id][name] = get elem, name for name in attrs
      # set data
      carrier = (data) ->
        # set value to dom element
        set = (elem, name, value) ->
          switch name.toString()
            when 'text' then elem.text value
            when 'html' then elem.html value
            when 'value' then elem.val value
            else elem.attr name, value
        # user data
        for id, attrs of model
          elem = $('#' + id)
          continue unless data[id]
          unless $.isArray attrs then set elem, attrs, data[id]
          else set elem, name, data[id][name] for name in attrs
      # post data
      $.post app._url + 'data', (JSON.stringify data), carrier, 'json'
  }

  # getting user event
  window.constructor::__defineGetter__ '_event', ->
