context = window
@JamBlasterNameDialog = React.createClass({

  mixins: [Reflux.listenTo(@AppStore, "onAppInit")]
  teacher: null

  beforeShow: (args) ->
    logger.debug("JamBlasterNameDialog.beforeShow", args.d1)
    @setState({name: args.d1})


  afterHide: () ->

  onAppInit: (@app) ->
    dialogBindings = {
      'beforeShow': @beforeShow,
      'afterHide': @afterHide
    };

    @app.bindDialog('jamblaster-name-dialog', dialogBindings);

  getInitialState: () ->
    {
      name: ''
    }


  componentDidMount: () ->
    @root = $(@getDOMNode())
    @dialog = @root.closest('.dialog')

  doCancel: (e) ->
    e.preventDefault()
    @app.layout.closeDialog('jamblaster-name-dialog', true);

  onNameChange: (e) ->

    @setState({name: $(e.target).val()})

  updateName: (e) ->
    e.preventDefault()

    # validate

    name = @root.find('.name').val()

    characterMatch = /^[^a-z0-9,' -]+$/i

    if name.length == 0 || name == ''
      context.JK.Banner.showAlert('invalid name', 'Please specify a name.')
      return
    else if name.length < 2
      context.JK.Banner.showAlert('invalid name', 'Please specify a name at least 3 characters long.')
      return
    else if name.length > 63
      context.JK.Banner.showAlert('invalid name', 'The name must be less than 64 characters long.')
      return
    else if characterMatch.test(name)
      context.JK.Banner.showAlert('invalid name',
        'The can only contain A-Z, 0-9, commas, apostrophes, spaces, or hyphens.')
      return

    result = context.jamClient.setJBName(name.trim())

    if !result
      context.JK.Banner.showAlert('unable to set the name',
        'Please email support@jamkazam.com and let us know the name you are specifying unsuccessfully, or refresh the page and try again.')
    else
      @app.layout.closeDialog('jamblaster-name-dialog')
  render: () ->
    `<div>
      <div className="content-head">
        <img className="content-icon" src="/assets/content/icon_add.png" height={19} width={19}/>

        <h1>update name of JamBlaster</h1>
      </div>
      <div className="dialog-inner">

        <p className="help-text">You can change the display name for this JamBlaster. The name can only contain A-Z, 0-9, commas, apostrophes,
          spaces, or hyphens. A valid example: "John Doe's JamBlaster"</p>

        <div className="field">
        <label>JamBlaster Name:</label>
        <input className="name" type="text" value={this.state.name} onChange={this.onNameChange}></input>
        </div>

        <div className="actions">
          <a onClick={this.doCancel} className="button-grey">CANCEL</a>
          <a onClick={this.updateName} className="button-orange name">UPDATE</a>
        </div>
      </div>
    </div>`

})