/* ***** BEGIN LICENSE BLOCK *****
 * Distributed under the BSD license:
 *
 * Copyright (c) 2012, Ajax.org B.V.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of Ajax.org B.V. nor the
 *       names of its contributors may be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL AJAX.ORG B.V. BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * ***** END LICENSE BLOCK ***** */

define('ace/mode/monkey', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text', 'ace/tokenizer', 'ace/mode/monkey_highlight_rules', 'ace/mode/matching_brace_outdent', 'ace/mode/folding/cstyle'], function(require, exports, module) {


var oop = require("../lib/oop");
var TextMode = require("./text").Mode;
var Tokenizer = require("../tokenizer").Tokenizer;
var MonkeyHighlightRules = require("./monkey_highlight_rules").MonkeyHighlightRules;
var MatchingBraceOutdent = require("./matching_brace_outdent").MatchingBraceOutdent;
var FoldMode = require("./folding/cstyle").FoldMode;

var Mode = function() {
    this.HighlightRules = MonkeyHighlightRules;
    this.$outdent = new MatchingBraceOutdent();
    this.foldingRules = new FoldMode();
};
oop.inherits(Mode, TextMode);

(function() {
    this.lineCommentStart = "'";
    this.blockComment = {start: "#Rem", end: "#End"};
}).call(Mode.prototype);

exports.Mode = Mode;
});define('ace/mode/monkey_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/lib/lang', 'ace/mode/doc_comment_highlight_rules', 'ace/mode/text_highlight_rules'], function(require, exports, module) {
    

    var oop = require("../lib/oop");
    var lang = require("../lib/lang");
    var DocCommentHighlightRules = require("./doc_comment_highlight_rules").DocCommentHighlightRules;
    var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules;

    var MonkeyHighlightRules = function () {

        var constantsJoy = (
            "JOY_A|JOY_B|JOY_X|JOY_Y|JOY_LB|JOY_RB|JOY_BACK|JOY_START|JOY_LEFT|JOY_UP|JOY_RIGHT|JOY_DOWN"
            );
        var constantsMouse = (
            "MOUSE_LEFT|MOUSE_RIGHT|MOUSE_MIDDLE"
            );
        var constantsKey = (
            "KEY_BACKSPACE|KEY_TAB|KEY_ENTER|KEY_ESCAPE|KEY_SPACE|KEY_SHIFT|KEY_CONTROL|" +
                "KEY_PAGEUP|KEY_PAGEDOWN|KEY_END|KEY_HOME|KEY_LEFT|KEY_UP|KEY_RIGHT|KEY_DOWN|KEY_INSERT|KEY_DELETE|" +
                "F0|F1|F2|F3|F4|F5|F6|F7|F8|F9|F10|F11|F12|" +
                "TILDE|MINUS|EQUALS|OPENBRACKET|CLOSEBRACKET|BACKSLASH|SEMICOLON|QUOTES|COMMA|PERIOD|SLASH|LMB|RMB|MMB|"
            );
        var constantsTouch = (
            "TOUCH0|TOUCH1|TOUCH2|TOUCH3|TOUCH4|TOUCH5|TOUCH6|TOUCH7|TOUCH8|TOUCH9|TOUCH10|" +
                "TOUCH11|TOUCH12|TOUCH13|TOUCH14|TOUCH15|TOUCH16|TOUCH17|TOUCH18|TOUCH19|TOUCH20|" +
                "TOUCH21|TOUCH22|TOUCH23|TOUCH24|TOUCH25|TOUCH26|TOUCH27|TOUCH28|TOUCH29|TOUCH30|TOUCH31|TOUCH32"
            );

        var keywords = (
            "Abstract|ACos|ASin|ATan|ATan2|Abs|AccelX|AccelY|AccelZ|AddFirst|AddLast|App|Array|" +
                "Backwards|Bool|Case|Ceil|ChannelState|Clamp|Class|Cls|Compare|Const|Contains|Continue|Copy|Cos|Count|Clear|" +
                "DefaultFlags|DeviceWidth|DeviceHeight|Discard|DrawCircle|DrawEllipse|DrawImage|DrawImageRect|DrawLine|DrawOval|DrawPoint|DrawPoly|DrawRect|DrawText|" +
                "Eachin|Extends|Extern|EndsWith|Error|Exit|" +
                "False|Field|FindLast|First|FloatMap|FloatSet|Floor|For|Forever|Frames|FromChar|Function|" +
                "Get|GetAlpha|GetBlend|GetChar|GetColor|GetFont|GetMatrix|GetScissor|Global|GrabImage|" +
                "HandleX|HandleY|Height|" +
                "Image|Implements|Import|Include|Inline|Interface|IntMap|IntSet|IsEmpty|" +
                "Join|JoyDown|JoyHit|JoyX|JoyY|JoyZ|Key|KeyDown|KeyHit|Keys|" +
                "Last|Length|List|Log|LoadIMage|LoadSound|LoadState|LoadString|Local|" +
                "Map|Max|Method|Millisecs|Min|Mod|Module|MouseDown|MouseHit|MouseX|MouseY|Mousein|" +
                "Native|New|Next|Node|Null|" +
                "ObjectEnumerator|OnCreate|OnLoading|OnRender|OnResume|OnSuspend|OnUpdate|" +
                "PlaySound|PopMatrix|Pow|Print|Private|Property|Public|PushMatrix|" +
                "Remove|RemoveEach|RemoveFirst|RemoveLast|Repeat|Replace|Return|Rnd|Rotate|" +
                "SaveState|Scale|Seed|Selected|Self|SetAlpha|SetBlend|SetChannelPan|SetChannelRate|SetChannelVolume" +
                "SetColor|SetFont|SetHandle|SetMatrix|SetScissor|SetUpdateRate|Sgn|Shl|Shr|Sin|Sound|Split|Sqrt|" +
                "StartsWith|Step|StopChannel|Strict|String|StringMap|StringSet|Super|" +
                "Tan|Then|ToLower|ToUpper|TouchDown|TouchHit|TouchX|TouchY|Transform|Translate|Trim|True|" +
                "Until|" +
                "Value|ValueForKey|Values|Void|Width"
            );
        var keywordsControl = (
            "If|Else|Else If|Elseif|End|End If|Endif"
            );
        var keywordsOperator = (
            "And|Not"
            );

        var keywordMapper = this.createKeywordMapper({
            "variable.language": "this",
            "keyword.other.commands.monkey": keywords,
            "keyword.control": keywordsControl,
            "keyword.opeator": keywordsOperator,
            "constant.language.joy.monkey": constantsJoy,
            "constant.language.key.monkey": constantsKey,
            "constant.language.mouse.monkey": constantsMouse,
            "constant.langauge.touch.monkey": constantsTouch
        }, "identifier");

        this.$rules = {
            start: [
                {
                    token: 'comment.block.rem.monkey',
                    regex: '(#Rem|#rem|#REM)',
                    next: 'comment'
                },
                {
                    token: 'comment.line.apostrophe.monkey',
                    regex: '(\')([^\n]+)?'
                },
                {
                    caseInsensitive: true,
                    token: 'string.unquoted.module.monkey',
                    regex: '\\b(import)\\s+((?:[a-zA-Z_]\\w*\\.?)+)\\b'
                },
                {
                    caseInsensitive: true,
                    token: 'string.quoted.double.monkey',
                    regex: '\\b(import)\\s+'
                },
                {
                    caseInsensitive: true,
                    token: [
                        'keyword',
                        'entity.other.class',
                        'keyword',
                        'entity.other.inherited-class',
                        'keyword',
                        'entity.other.implements',
                        'keyword'
                    ],
                    regex: '\\b(class\\s)+([a-zA-Z_]\\w*)(?:(\\sextends\\s)+([a-zA-Z_]\\w*))?(?:(\\simplements\\s)+([a-zA-Z_]\\w*))?(?:(\\sfinal|\\sabstract))?\\b'
                },
                {
                    token: "string", // single line
                    regex: '["](?:(?:\\\\.)|(?:[^"\\\\]))*?["]'
                },
                {
                    token: 'constant.numeric.integer.hexadecimal.monkey', // hex
                    regex: '(\\$[0-9a-fA-F]{1,16})'
                },
                {
                    token: keywordMapper,
                    regex: "[a-zA-Z_$][a-zA-Z0-9_$]*\\b"
                },
                {
                    token: "constant.numeric", // float
                    regex: "[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?\\b"
                },
                {
                    token: "keyword.operator",
                    regex: "!|\\$|%|&|\\*|\\-\\-|\\-|\\+\\+|\\+|~|===|==|=|!=|!==|<=|>=|<<=|>>=|>>>=|<>|<|>|!|&&|\\|\\||\\?\\:|\\*=|%=|\\+=|\\-=|&=|\\^="
                }
            ],
            comment: [
                {
                    token: "comment.block.rem.monkey", // closing comment
                    regex: ".*?(#End|#end|#END)",
                    next: "start"
                },
                {
                    token: ['comment.block.rem.monkey', 'url.monkey', 'comment.block.rem.monkey'],
                    regex: '(.*)(http://[^ "\'()\\[\\]]*(?=$|\\b))(.*)'
                },
                {
                    token: "comment.block.rem.monkey", // comment spanning whole line
                    regex: ".+"
                }
            ]
        };

        this.embedRules(DocCommentHighlightRules, "doc-",
            [ DocCommentHighlightRules.getEndRule("start") ]);
    };

    oop.inherits(MonkeyHighlightRules, TextHighlightRules);

    exports.MonkeyHighlightRules = MonkeyHighlightRules;
});

define('ace/mode/doc_comment_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text_highlight_rules'], function(require, exports, module) {


var oop = require("../lib/oop");
var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules;

var DocCommentHighlightRules = function() {

    this.$rules = {
        "start" : [ {
            token : "comment.doc.tag",
            regex : "@[\\w\\d_]+" // TODO: fix email addresses
        }, {
            token : "comment.doc.tag",
            regex : "\\bTODO\\b"
        }, {
            defaultToken : "comment.doc"
        }]
    };
};

oop.inherits(DocCommentHighlightRules, TextHighlightRules);

DocCommentHighlightRules.getStartRule = function(start) {
    return {
        token : "comment.doc", // doc comment
        regex : "\\/\\*(?=\\*)",
        next  : start
    };
};

DocCommentHighlightRules.getEndRule = function (start) {
    return {
        token : "comment.doc", // closing comment
        regex : "\\*\\/",
        next  : start
    };
};


exports.DocCommentHighlightRules = DocCommentHighlightRules;

});

define('ace/mode/matching_brace_outdent', ['require', 'exports', 'module' , 'ace/range'], function(require, exports, module) {


var Range = require("../range").Range;

var MatchingBraceOutdent = function() {};

(function() {

    this.checkOutdent = function(line, input) {
        if (! /^\s+$/.test(line))
            return false;

        return /^\s*\}/.test(input);
    };

    this.autoOutdent = function(doc, row) {
        var line = doc.getLine(row);
        var match = line.match(/^(\s*\})/);

        if (!match) return 0;

        var column = match[1].length;
        var openBracePos = doc.findMatchingBracket({row: row, column: column});

        if (!openBracePos || openBracePos.row == row) return 0;

        var indent = this.$getIndent(doc.getLine(openBracePos.row));
        doc.replace(new Range(row, 0, row, column-1), indent);
    };

    this.$getIndent = function(line) {
        return line.match(/^\s*/)[0];
    };

}).call(MatchingBraceOutdent.prototype);

exports.MatchingBraceOutdent = MatchingBraceOutdent;
});

define('ace/mode/folding/cstyle', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/range', 'ace/mode/folding/fold_mode'], function(require, exports, module) {


var oop = require("../../lib/oop");
var Range = require("../../range").Range;
var BaseFoldMode = require("./fold_mode").FoldMode;

var FoldMode = exports.FoldMode = function(commentRegex) {
    if (commentRegex) {
        this.foldingStartMarker = new RegExp(
            this.foldingStartMarker.source.replace(/\|[^|]*?$/, "|" + commentRegex.start)
        );
        this.foldingStopMarker = new RegExp(
            this.foldingStopMarker.source.replace(/\|[^|]*?$/, "|" + commentRegex.end)
        );
    }
};
oop.inherits(FoldMode, BaseFoldMode);

(function() {

    this.foldingStartMarker = /(\{|\[)[^\}\]]*$|^\s*(\/\*)/;
    this.foldingStopMarker = /^[^\[\{]*(\}|\])|^[\s\*]*(\*\/)/;

    this.getFoldWidgetRange = function(session, foldStyle, row, forceMultiline) {
        var line = session.getLine(row);
        var match = line.match(this.foldingStartMarker);
        if (match) {
            var i = match.index;

            if (match[1])
                return this.openingBracketBlock(session, match[1], row, i);
                
            var range = session.getCommentFoldRange(row, i + match[0].length, 1);
            
            if (range && !range.isMultiLine()) {
                if (forceMultiline) {
                    range = this.getSectionRange(session, row);
                } else if (foldStyle != "all")
                    range = null;
            }
            
            return range;
        }

        if (foldStyle === "markbegin")
            return;

        var match = line.match(this.foldingStopMarker);
        if (match) {
            var i = match.index + match[0].length;

            if (match[1])
                return this.closingBracketBlock(session, match[1], row, i);

            return session.getCommentFoldRange(row, i, -1);
        }
    };
    
    this.getSectionRange = function(session, row) {
        var line = session.getLine(row);
        var startIndent = line.search(/\S/);
        var startRow = row;
        var startColumn = line.length;
        row = row + 1;
        var endRow = row;
        var maxRow = session.getLength();
        while (++row < maxRow) {
            line = session.getLine(row);
            var indent = line.search(/\S/);
            if (indent === -1)
                continue;
            if  (startIndent > indent)
                break;
            var subRange = this.getFoldWidgetRange(session, "all", row);
            
            if (subRange) {
                if (subRange.start.row <= startRow) {
                    break;
                } else if (subRange.isMultiLine()) {
                    row = subRange.end.row;
                } else if (startIndent == indent) {
                    break;
                }
            }
            endRow = row;
        }
        
        return new Range(startRow, startColumn, endRow, session.getLine(endRow).length);
    };

}).call(FoldMode.prototype);

});

define('ace/mode/matching_brace_outdent', ['require', 'exports', 'module' , 'ace/range'], function(require, exports, module) {


var Range = require("../range").Range;

var MatchingBraceOutdent = function() {};

(function() {

    this.checkOutdent = function(line, input) {
        if (! /^\s+$/.test(line))
            return false;

        return /^\s*\}/.test(input);
    };

    this.autoOutdent = function(doc, row) {
        var line = doc.getLine(row);
        var match = line.match(/^(\s*\})/);

        if (!match) return 0;

        var column = match[1].length;
        var openBracePos = doc.findMatchingBracket({row: row, column: column});

        if (!openBracePos || openBracePos.row == row) return 0;

        var indent = this.$getIndent(doc.getLine(openBracePos.row));
        doc.replace(new Range(row, 0, row, column-1), indent);
    };

    this.$getIndent = function(line) {
        return line.match(/^\s*/)[0];
    };

}).call(MatchingBraceOutdent.prototype);

exports.MatchingBraceOutdent = MatchingBraceOutdent;
});

define('ace/mode/folding/cstyle', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/range', 'ace/mode/folding/fold_mode'], function(require, exports, module) {


var oop = require("../../lib/oop");
var Range = require("../../range").Range;
var BaseFoldMode = require("./fold_mode").FoldMode;

var FoldMode = exports.FoldMode = function(commentRegex) {
    if (commentRegex) {
        this.foldingStartMarker = new RegExp(
            this.foldingStartMarker.source.replace(/\|[^|]*?$/, "|" + commentRegex.start)
        );
        this.foldingStopMarker = new RegExp(
            this.foldingStopMarker.source.replace(/\|[^|]*?$/, "|" + commentRegex.end)
        );
    }
};
oop.inherits(FoldMode, BaseFoldMode);

(function() {

    this.foldingStartMarker = /(\{|\[)[^\}\]]*$|^\s*(\/\*)/;
    this.foldingStopMarker = /^[^\[\{]*(\}|\])|^[\s\*]*(\*\/)/;

    this.getFoldWidgetRange = function(session, foldStyle, row, forceMultiline) {
        var line = session.getLine(row);
        var match = line.match(this.foldingStartMarker);
        if (match) {
            var i = match.index;

            if (match[1])
                return this.openingBracketBlock(session, match[1], row, i);
                
            var range = session.getCommentFoldRange(row, i + match[0].length, 1);
            
            if (range && !range.isMultiLine()) {
                if (forceMultiline) {
                    range = this.getSectionRange(session, row);
                } else if (foldStyle != "all")
                    range = null;
            }
            
            return range;
        }

        if (foldStyle === "markbegin")
            return;

        var match = line.match(this.foldingStopMarker);
        if (match) {
            var i = match.index + match[0].length;

            if (match[1])
                return this.closingBracketBlock(session, match[1], row, i);

            return session.getCommentFoldRange(row, i, -1);
        }
    };
    
    this.getSectionRange = function(session, row) {
        var line = session.getLine(row);
        var startIndent = line.search(/\S/);
        var startRow = row;
        var startColumn = line.length;
        row = row + 1;
        var endRow = row;
        var maxRow = session.getLength();
        while (++row < maxRow) {
            line = session.getLine(row);
            var indent = line.search(/\S/);
            if (indent === -1)
                continue;
            if  (startIndent > indent)
                break;
            var subRange = this.getFoldWidgetRange(session, "all", row);
            
            if (subRange) {
                if (subRange.start.row <= startRow) {
                    break;
                } else if (subRange.isMultiLine()) {
                    row = subRange.end.row;
                } else if (startIndent == indent) {
                    break;
                }
            }
            endRow = row;
        }
        
        return new Range(startRow, startColumn, endRow, session.getLine(endRow).length);
    };

}).call(FoldMode.prototype);

});

define('ace/mode/doc_comment_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text_highlight_rules'], function(require, exports, module) {


var oop = require("../lib/oop");
var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules;

var DocCommentHighlightRules = function() {

    this.$rules = {
        "start" : [ {
            token : "comment.doc.tag",
            regex : "@[\\w\\d_]+" // TODO: fix email addresses
        }, {
            token : "comment.doc.tag",
            regex : "\\bTODO\\b"
        }, {
            defaultToken : "comment.doc"
        }]
    };
};

oop.inherits(DocCommentHighlightRules, TextHighlightRules);

DocCommentHighlightRules.getStartRule = function(start) {
    return {
        token : "comment.doc", // doc comment
        regex : "\\/\\*(?=\\*)",
        next  : start
    };
};

DocCommentHighlightRules.getEndRule = function (start) {
    return {
        token : "comment.doc", // closing comment
        regex : "\\*\\/",
        next  : start
    };
};


exports.DocCommentHighlightRules = DocCommentHighlightRules;

});
