###
Neft object
###
@__macos__ = {}

###
Global object
###
@global = @

###
Console
###
do =>
    sendLog = (type, args) ->
        msg = "[#{type}] " + Array::join.call args, ' '
        webkit?.messageHandlers.log.postMessage msg
        return

    console.log = do (_super = console.log) -> ->
        sendLog 'LOG', arguments
        _super arguments...
    console.info = do (_super = console.info) -> ->
        sendLog 'INFO', arguments
        _super arguments...
    console.warn = do (_super = console.warn) -> ->
        sendLog 'WARN', arguments
        _super arguments...
    console.error = do (_super = console.error) -> ->
        sendLog 'ERROR', arguments
        _super arguments...

###
Timers
###
setImmediate = do ->
    ready = false
    running = false
    queue = []

    callAll = ->
        running = false
        length = queue.length
        for i in [0...length] by 2
            func = queue.shift()
            args = queue.shift()
            Neft.tryCatch.tryCall func, null, args
        return

    update = do ->
        unless Mutation = window.MutationObserver or window.WebKitMutationObserver
            return

        calls = 0
        observer = new Mutation callAll
        element = document.createTextNode ''
        observer.observe element, characterData: true

        ->
            element.data = ++calls%2 ? "a" : "b"

    update ||= do ->
        if window?.setImmediate or not MessageChannel?
            return

        channel = new MessageChannel()
        channel.port1.onmessage = callAll

        ->
            channel.port2.postMessage 0

    update ||= do ->
        ->
            setTimeout callAll, 0

    # Firefox sometimes calls setImmediate before the code execution end
    setTimeout ->
        ready = true
        callAll()

    (func) ->
        argc = arguments.length
        if argc > 1
            args = new Array argc - 1
            for i in [1...argc] by 1
                args[i - 1] = arguments[i]
        queue.push func, args
        if ready and not running
            update()
            running = true
        return

###
Neft code
###
`{{&neftCode}}`
@Neft = Neft

###
App code
###
`{{&appCode}}`
