 http = require('http')
 hbs = require('hbs')
 pagehandler = require('./page.coffee')
-_ = require('../../../client/js/underscore-min.js')
 favicon = require('./favicon.coffee')
 passport = require('passport')
 OpenIDstrat = require('passport-openid').Strategy

    # actionCB handles all of the possible actions to be taken on a page,
    actionCB = (page) ->
      console.log page if argv.debug
      switch action.type
        when 'move'
          page.story = _(action.order).map((i) ->
            _(page.story).find( (story) ->
              console.log(i, story) if argv.debug
              i is story.id
            )
          )
          
        when 'add'
          before = 0
          for item, index in page.story
            if item.id is action.after
              before = index
          page.story[before...before] = action.item

        when 'remove'
          page.story = (item for item in page.story when item?.id isnt action.id)

        when 'edit'
          page.story = ((if item.id is action.id then action.item else item) for item in page.story)

        else
          console.log "Unfamiliar action: #{action}"
      if not page.journal
        page.journal = []
      page.journal.push(action)

    )
  )

  ###### Json Routes
  # These handle fetching local and remote json pages.
  # Local pages are handled by the pagehandler, module.
  app.get(///^/([a-z0-9-]+)\.json$///, (req, res) ->
    file = req.params[0]
    pagehandler.get(file, (page) =>
      res.json(page)
    )
  )

  # Remote pages use the http client to retrieve the page
  # and sends it to the client.  TODO: consider caching remote pages locally.
  app.get(///^/remote/([a-zA-Z0-9:\.-]+)/([a-z0-9-]+)\.json$///, (req, res) ->
    getopts = {
      host: req.params[0]
      port: 80
      path: "/#{req.params[1]}.json"
    }
    # TODO: This needs more robust error handling, just trying to
    # keep it from taking down the server.
    http.get(getopts, (resp) ->
      responsedata = ''
      resp.on('data', (chunk) ->
        responsedata += chunk
      )
      resp.on('error', (e) ->
        console.log("Error: #{e}")
      )
      resp.on('end', ->
        res.json(JSON.parse(responsedata))
      )
    ).on('error', (e) ->
      console.log "Error: #{e}"
    )
  )

  ###### Favicon Routes
  # Local favicons are handled by the favicon module.
  app.get('/favicon.png', (req,res) ->
    favicon.get(path.join(argv.status, "favicon.png"), (loc) ->
      res.sendfile(loc)
    )
  )

  # Remote favicons redirect to the server they are needed from.
  app.get(///^/remote/([a-zA-Z0-9:\.-]+/favicon.png)$///, (req, res) ->
        res.redirect('remotefav')
  )
