/* jsmin.js - 2006-08-31
Author: Franck Marcia
This work is an adaptation of jsminc.c published by Douglas Crockford.
Permission is hereby granted to use the Javascript version under the
same conditions as the jsmin.c on which it is based.

jsmin.c
2006-05-04

Copyright (c) 2002 Douglas Crockford  (www.crockford.com)

Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:

The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.

The Software shall be used for Good, not Evil.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Update:
    add level:
        1: minimal, keep linefeeds if single
        2: normal, the standard algorithm
        3: agressive, remove any linefeed and doesn't take care of
           potential missing semicolons (can be regressive)
    store stats
        jsmin.oldSize
        jsmin.newSize
*/
"use strict";
String.prototype.has = function (c) {
    return this.indexOf(c) > -1;
};
var jsmin = function (comment, input, level, type, slop) {
    switch (type) {
    case "css":
        if (new RegExp(/if\s*\(\s*[a-z0-9]+\s*((={2,3})|(\!={1,2}))\s*[a-z0-9]+\s*\)\s*\{/i).test(input) === true && new RegExp(/var\s+[a-z]+[a-z0-9]*/i).test(input) === true) {
            return "Error: Input appears to be JavaScript, but the application is set to minify CSS.";
        } else if (new RegExp(/>\s*<\/[a-z]+>/i).test(input) === true && new RegExp(/[a-z]+[a-z0-9]*\s*\{\s*[a-z]+(\-[a-z]+)*\s*\:\s*[a-z]+(\-[a-z]+)*\s*;/i).test(input) === false) {
            return "Error: Input appears to be markup, but the application is set to minify CSS.";
        }
        if (input !== undefined) {
            input = input.replace(/http:\/\//g, "http:xx");
        }
        break;
    case "javascript":
        if (new RegExp(/>\s*<\/[a-z]+>/i).test(input) === true && new RegExp(/document\.write/).test(input) === false && new RegExp(/if\s*\(\s*[a-z0-9]+\s*((={2,3})|(\!={1,2}))\s*[a-z0-9]+\s*\)\s*\{/i).test(input) === false) {
            return "Error: Input appears to be markup, but the application is set to minify JavaScript.";
        } else if (new RegExp(/[a-z]+[a-z0-9]*\s*\{\s*[a-z]+(\-[a-z]+)*\s*\:\s*[a-z]+(\-[a-z]+)*\s*;/i).test(input) === true && new RegExp(/if\s*\(\s*[a-z0-9]+\s*((={2,3})|(\!={1,2}))\s*[a-z0-9]+\s*\)\s*\{/i).test(input) === false) {
            return "Error: Input appears to be CSS, but the application is set to minify JavaScript.";
        }
        if (input !== undefined) {
            input = input.replace(/\/\/(\s)*-->/g, "//-->");
        }
        break;
    default:
        return "Error: The type argument is not provided a value of either 'css' or 'javascript'.";
    }
    if (input === undefined) {
        input = comment;
        comment = '';
        level = 2;
    } else if (level === undefined || level < 1 || level > 3) {
        level = 2;
    }
    if (comment.length > 0) {
        comment += '\n';
    }
    var ret, error = "",
    a = '',
    b = '',
    EOF = -1,
    LETTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz',
    DIGITS = '0123456789',
    OTHERS, ALNUM, theLookahead = EOF,

    //isAlphanum -- return true if the character is a letter, digit,
    //underscore, dollar sign, or non-ASCII character.
    isAlphanum = function (c) {
        return c !== EOF && (ALNUM.has(c) || c.charCodeAt(0) > 126);
    },
    isValue = function (c) {
        return c !== EOF && (']"\')'.has(c));
    },

    //get -- return the next character. Watch out for lookahead. If
    //the character is a control character, translate it to a space
    //or linefeed.
    get = function () {
        var c = theLookahead;
        if (get.i === get.l) {
            return EOF;
        }
        theLookahead = EOF;
        if (c === EOF) {
            c = input.charAt(get.i);
            get.i += 1;
        }
        if (c >= ' ' || c === '\n') {
            return c;
        }
        if (c === '\r') {
            return '\n';
        }
        return ' ';
    },

    //This function corrects a faulty side effect of appending
    //semicolons directly between ")" and "\n" characters.
    ifcorrect = function (x) {
        var i, z, a, b, q, c = [],
        d = [],
        quotefinder = function (e, f) {
            var g, h, j, m;
            if (e[0] < f[0]) {
                for (g = 0; g < e.length; g += 2) {
                    for (j = 0; j < f.length; j += 1) {
                        if (e[g] < f[j] && f[j] < e[g + 1]) {
                            f.splice(j, 1);
                        }
                    }
                }
                for (g = 0; g < f; g += 2) {
                    for (j = 0; j < e.length; j += 1) {
                        if (e[j] > f[g] && e[j] < f[g + 1]) {
                            e.splice(j, 1);
                        }
                    }
                }
            } else {
                for (g = 0; g < f; g += 2) {
                    for (j = 0; j < e.length - 1; j += 1) {
                        if (e[j] > f[g] && e[j] < f[g + 1]) {
                            e.splice(j, 1);
                        }
                    }
                }
                for (g = 0; g < e.length; g += 2) {
                    for (j = 0; j < f.length; j += 1) {
                        if (f[j] > e[g] && f[j] < e[g + 1]) {
                            f.splice(j, 1);
                        }
                    }
                }
            }
            if (e.length >= f.length) {
                h = e.length;
            } else {
                h = f.length;
            }
            m = e.concat(f);
            for (g = 0; g < m.length; g += 1) {
                if (e[g] < f[g]) {
                    f.splice(g, 0, e[g]);
                    if (e[g + 1] < f[g]) {
                        f.splice(g, 0, e[g + 1]);
                    }
                } else {
                    for (j = g; j < m.length; j += 1) {
                        if (e[g] < f[j]) {
                            f.splice(j, 0, e[g]);
                            break;
                        }
                    }
                }
            }
            return f;
        },
        quotetest = function (y) {
            var e;
            for (e = 0; e < q.length; e += 2) {
                if (y > q[e] && y < q[e + 1]) {
                    return true;
                }
            }
            return false;
        },
        correction = function () {
            for (a = i; a < x.length; a += 1) {
                if (x[a] === ')') {
                    break;
                }
            }
            if (x[a + 1] === ';' && quotetest(a + 1) === false) {
                x[a + 1] = '';
            }
        };
        x = x.split('');
        for (z = 0; z < x.length; z += 1) {
            if (x[z] === "\"") {
                c.push(z);
            }
            if (x[z] === '\'') {
                d.push(z);
            }
        }
        q = quotefinder(c, d);
        for (i = 0; i < x.length; i += 1) {
            b = x[i] + x[i + 1] + x[i + 2] + x[i + 3] + x[i + 4] + x[i + 5] + x[i + 6] + x[i + 7];
            if ((b === 'function' || b.slice(0, 2) === 'if' || b.slice(0, 5) === 'while' || b.slice(0, 3) === 'for') && quotetest(i) === false) {
                correction();
            } else if (((x[i] !== "+" && x[i + 1] === "+" && x[i + 2] === ";") && quotetest(i + 2) === false) || ((x[i] !== "-" && x[i + 1] === "-" && x[i + 2] === ";") && quotetest(i + 2) === false)) {
                x[i + 2] = "";
            } else if ((((x[i] === ";" || x[i] === '\n') && x[i + 1] === "+" && x[i + 2] !== "+") && quotetest(i + 2) === false) || ((x[i] === ";" && x[i + 1] === "-" && x[i + 2] !== "-") && quotetest(i + 2) === false)) {
                x[i] = "";
            }
        }
        if (x[0] === ';') {
            x[0] = '';
        }
        return x.join('');
    },

    //peek -- get the next character without getting it.
    peek = function () {
        theLookahead = get();
        return theLookahead;
    },

    //next -- get the next character, excluding comments. peek() is
    //used to see if a '/' is followed by a '/' or '*'.
    next = function () {
        var c = get();
        if (c === '/') {
            switch (peek()) {
            case '/':
                for (;;) {
                    c = get();
                    if (c <= '\n') {
                        return c;
                    }
                }
                break;
            case '*':
                get();
                for (;;) {
                    switch (get()) {
                    case "'":
                        c = get().replace(/'/, '');
                        break;
                    case '"':
                        c = get().replace(/"/, '');
                        break;
                    case '*':
                        if (peek() === '/') {
                            get();
                            return ' ';
                        }
                        break;
                    case EOF:
                        error = 'Error: Unterminated JavaScript comment.';
                        return error;
                    }
                }
                break;
            default:
                return c;
            }
        }
        return c;
    },

    //action -- do something! What you do is determined by the
    //argument:
    //   1   Output A. Copy B to A. Get the next B.
    //   2   Copy B to A. Get the next B. (Delete A).
    //   3   Get the next B. (Delete B).
    //action treats a string as a single character. Wow!
    //action recognizes a regular expression if it is preceded by
    //( or , or =.
    action = function (d) {
        var r = [];
        if (d === 1) {
            r.push(a);
        }
        if (d < 3) {
            a = b;
            if (a === '\'' || a === '"') {
                for (;;) {
                    r.push(a);
                    a = get();
                    if (a === b) {
                        break;
                    }
                    if (a <= '\n') {
                        error = 'Error: This does not appear to be JavaScript. Try submitting as plain text or markup.';
                        return error;
                    }
                    if (a === '\\') {
                        r.push(a);
                        a = get();
                    }
                }
            }
        }
        b = next();
        if (b === '/' && '(,=:[!&|'.has(a)) {
            r.push(a);
            r.push(b);
            for (;;) {
                a = get();
                if (a === '/') {
                    break;
                } else if (a === '\\') {
                    r.push(a);
                    a = get();
                } else if (a <= '\n') {
                    error = 'Error: unterminated JavaScript Regular Expression literal';
                    return error;
                }
                r.push(a);
            }
            b = next();
        }
        return r.join('');
    },

    //m -- Copy the input to the output, deleting the characters
    //which are insignificant to JavaScript. Comments will be
    //removed. Tabs will be replaced with spaces. Carriage returns
    //will be replaced with linefeeds.
    //Most spaces and linefeeds will be removed.
    m = function () {
        if (error !== "") {
            return error;
        }
        var r = [];
        a = '\n';
        r.push(action(3));
        while (a !== EOF) {
            if (a === ' ' && !(type === 'css' && b === '#')) {
                if (isAlphanum(b)) {
                    r.push(action(1));
                } else {
                    r.push(action(2));
                }
            } else if (a === '\n') {
                switch (b) {
                case '{':
                case '[':
                case '(':
                case '+':
                case '-':
                    r.push(action(1));
                    break;
                case ' ':
                    if (slop === 'slop') {
                        r.push(action(3) + action(2) + ';');
                    } else {
                        r.push(action(3));
                    }
                    break;
                default:
                    if (isAlphanum(b)) {
                        r.push(action(1));
                    } else {
                        if (level === 1 && b !== '\n') {
                            r.push(action(1));
                        } else {
                            r.push(action(2));
                        }
                    }
                }
            } else {
                switch (b) {
                case ' ':
                    if (isAlphanum(a)) {
                        r.push(action(1));
                        break;
                    }
                    r.push(action(3));
                    break;
                case '\n':
                    if (level === 1 && a !== '\n') {
                        r.push(action(1));
                    } else if (a === '}') {
                        if (level === 3) {
                            r.push(action(3));
                        } else {
                            r.push(action(1));
                        }
                        //I altered this block so that a semicolon
                        //is appended to the end of lines that are
                        //not terminated with a semicolon.  This
                        //prevents single line conditions from
                        //being merged without any sort of
                        //separation.  The original code is
                        //r.push(action(1)); before the else.  This
                        //block also references the new isValue
                        //function.  The if block must continue to
                        //exist or every line feed will be replaced
                        //with a semicolon.
                    } else if (isAlphanum(a) || isValue(a)) {
                        if (slop === 'slop') {
                            r.push(action(3) + action(1) + ';');
                        } else {
                            r.push(action(3));
                        }
                    } else {
                        r.push(action(3));
                    }
                    break;
                default:
                    r.push(action(1));
                    break;
                }
            }
        }
        return r.join('');
    };
    if (type === "css") {
        OTHERS = '-._\\';
    } else {
        OTHERS = '_$//';
    }
    ALNUM = LETTERS + DIGITS + OTHERS;
    get.i = 0;
    get.l = input.length;
    if (slop === "slop") {
        ret = ifcorrect(m(input).replace(/\);\{/g, '){').replace(/;+\s*/g, ';').replace(/\);\+(?!\+)/g, ')+').replace(/\);\-(?!\-)/g, ')-').replace(/\s+\+(?!\+)/g, '+').replace(/\s+\-(?!\-)/g, '-').replace(/\s+((?=\+\+)|(?=\-\-))/g, ';'));
    } else {
        ret = m(input);
    }
    if (type === "css") {
        ret = ret.replace(/\: #/g, ":#").replace(/\; #/g, ";#").replace(/\, #/g, ",#").replace(/\s+/g, " ").replace(/\} /g, '}').replace(/\{ /g, '{').replace(/http:xx/g, "http://").replace(/\)/g, ") ").replace(/\) ;/g, ");");
    } else {
        ret = ret.replace(/x{2}-->/g, "//-->");
    }
    if (ret.charAt(0) === " " || ret.charAt(0) === "\n" || ret.charAt(0) === "\t") {
        ret = ret.slice(1, ret.length);
    }
    if (error !== "") {
        return error;
    } else {
        return comment + ret;
    }
};