﻿var qSyntax = {};
(function() {
    var _p = {};

    //simple span clear
    _p.clear = function(str) {
        return str.replace(/<span[^>]*>|<\/span>/gi, "");
    };

    //finds keywords and formats
    _p.format = function(html) {

        //keywords
        html = html.replace(/var|while|do|document|else|if|return|function|true|false|new|Date|Object|Number|Array|Boolean/g, function(match) { return "<span class='keyword' >" + match + "</span>"; });
        html = html.replace(/jLinq/g, function(match) { return "<span class='special' >" + _p.clear(match) + "</span>"; });
        //html = html.replace(/\/[^\n]*\/g?i?/g, function(match) { return "<span class='regexp' >" + _p.clear(match) + "</span>"; });
        html = html.replace(/\/{2}.*\n/g, function(match) { return "<span class='comment' >" + _p.clear(match) + "</span>"; });
        html = html.replace(/\"[^\"]*"/g, function(match) { return "<span class='quote' >" + _p.clear(match) + "</span>"; });

        //format each line
        html = html.split(/\n/g);
        for (var i = 0; i < html.length; i++) {
            html[i] = "<div class='jscript-row " +
                ((i % 2 != 0) ? "jscript-alt-row" : "") +
                "'>" + html[i] + "&nbsp;</div>";
        }

        //return the formatted code
        return html.join("");

    };

    //updates a set of elements
    qSyntax.update = function(selector, onTry) {
        if (!onTry) { onTry = function() { }; };

        //simple formatting for javascript
        $(selector).each(function(i, v) {

            //get the current blocks
            var code = $(v).find("pre");
            var html = code.text(); //.replace(/\s\.|\t\./g,"\n  .");
            var original = html;

            //if there is a try now button, save it for reuse
            $(v).find(".jscript-try a").attr("href", "javascript:void(0);")
                .click(function() {
                    $("#query").val(original);
                    onTry(original);
                });

            //update the new HTML
            var formatted = _p.format(html);
            code.html(formatted);

        });
    };

    //public formatting method
    qSyntax.format = _p.format;

})();