 
 # Can't figure out how else to use project-local module with Zappa.
 def mongoose: require "#{process.cwd()}/node_modules/mongoose"
+
+# Used for spherical calculations.  According to WolframAlpha.
+def radiusOfEarthMiles: 3956.6
+def feetInAMile: 5280
 
 get '/': ->
     # Define the mongoose schema.

# Use the current position to do a geospatial lookup of available cameras.
msg currentPosition: ->
    pos = [@position.coords.latitude, @position.coords.longitude]
    console.log {loc: $near: pos, $maxDistance: .1}
    app.CameraModel.find {loc: $near: pos, $maxDistance: .1}, (err, docs) =>
        if err
            send 'message', text: JSON.stringify err
        else
            send 'currentPosition', position: @position, cameras: docs

# Default view
view ->

        socket.on 'message', (raw) ->
            msg = JSON.parse raw
            console.log msg

            # A message from the server.
            if msg.message
                $('div[data-role="content"]')
                    .append $('<p>').text "#{msg.message.text}"

            # A result from the server based on current position.
            if msg.currentPosition
                # Show sensible units for accuracy.  Feet if under a half
                # mile, miles if over.
                if msg.currentPosition.position.coords.accuracy > 2640
                    accuracy = "#{(parseFloat(msg.currentPosition.position.coords.accuracy, 10) / 5280).toFixed 2} miles"
                else
                    accuracy = "#{msg.currentPosition.position.coords.accuracy} feet"

                $('p#stats').text """It looks like you're at
(#{msg.currentPosition.position.coords.latitude}, #{msg.currentPosition.position.coords.longitude}), within an accuracy of #{accuracy} and that there's at least #{msg.currentPosition.cameras.results.length} cameras within a distance of #{msg.currentPosition.cameras.maxDistance} miles at #{new Date(msg.currentPosition.position.timestamp)}."""

                for camera in msg.currentPosition.cameras.results
                    $('ul#cam-list').append($('script#cam-item').tmpl(camera))
                $('ul#cam-list').listview 'refresh'

