master
 1#= require service/embedly_service
 2
 3class csx.Views.My.Tutorials.NewView extends Marionette.ItemView
 4  template: JST['templates/my/tutorials/new']
 5  ui:
 6    url: '#tutorial_url'
 7    url_group: '#url-group'
 8    save_button: '#save-button'
 9    preview: '#preview-panel'
10    tags: '#tutorial_tags'
11
12  modelEvents:
13    'invalid': 'displayError'
14    'change:url': 'render'
15
16  events:
17    'change #tutorial_url': 'loadUrl'
18    "submit #new-tutorial": "save"
19
20  initialize: ->
21    @model = new @collection.model()
22    @service = new csx.EmbedlyService()
23
24  loadUrl: ->
25    if @model.isValidUrl(@ui.url.val())
26      @service.retrieve_info_on(@ui.url.val(), @updateTutorial)
27    @validate()
28
29  updateTutorial: (attributes) =>
30    @model.set
31      url: attributes.url
32      heading: attributes.title
33      description: attributes.description
34      image_url: if _.any(attributes.images) then attributes.images[0].url else ''
35      author: attributes.provider_name
36      author_url: attributes.provider_url
37
38  onRender: ->
39    @ui.tags.tagit({ availableTags: csx.Collections.Tag.pluck('name') })
40
41  validate: ->
42    @model.isValid()
43
44  displayError: (model, error) ->
45    @ui.save_button.attr('disabled', 'disabled')
46    @ui.preview.hide()
47    @ui.url_group.addClass("error")
48    errorTag = $('<span>').addClass('help-inline').text(error)
49    @ui.url_group.find('.controls').append(errorTag)
50
51  save: (event) ->
52    event.preventDefault()
53    event.stopPropagation()
54    @model.set('tags', @ui.tags.val())
55    @ui.save_button.attr('disabled', 'disabled')
56    @collection.create(@model,
57      success: @savedSuccessfully
58      error: @couldNotSave
59    )
60
61  savedSuccessfully: (cake) =>
62    window.location.hash = "tutorials"
63
64  couldNotSave: (cake, xhr) =>
65    @ui.save_button.removeAttr('disabled')
66    error = new csx.Views.ErrorView
67      el: @$('form#new-tutorial'),
68      attributesWithErrors: $.parseJSON(xhr.responseText)
69    error.render()