// sort-order.js
// Adds a selector for sort order to the top of the stream

(function($) {

    var plugin = Echo.createPlugin({
        "name": "SortOrder",
        "applications": ["Stream"],
        "init": function(plugin, application) {
            plugin.extendTemplate("Stream", '<div class="echo-stream-sortorder echo-secondaryColor"></div>', "insertAsFirstChild", "echo-stream-header", "SortOrder");
            plugin.extendRenderer("Stream", "sortorder", plugin.sortOrderRenderer, "SortOrder");
        }
    });

    plugin.addCss(".echo-stream-sortorder { float: left; }");

    plugin.sortOrderRenderer = function(element, dom) {
        var application = this;
        
        var newestFirst = $('<a href="#">Newest First</a>').click(function(e) {
            e.preventDefault();
            plugin.setParentSortOrder(application, "reverseChronological");
        }).appendTo(element);

        var oldestFirst = $('<a href="#">Oldest First</a>').click(function(e) {
            e.preventDefault();
            plugin.setParentSortOrder(application, "chronological");
        }).appendTo(element);

        var queryParts = plugin.splitQuery(application.config.get("query"));
        var currentSort = plugin.getSortOrder(queryParts.parents);
        if (currentSort === "chronological") {
            oldestFirst.addClass("selected");
        }
        else if (currentSort === "reverseChronological") {
            newestFirst.addClass("selected");
        }
    };

    plugin.setParentSortOrder = function(application, sort) {
        var queryParts = plugin.splitQuery(application.config.get("query"));
        queryParts.parents = plugin.addReplaceSortOrder(queryParts.parents, sort);
        application.config.set("query", queryParts.parents + queryParts.children);
        application.refresh();
    };

    plugin.splitQuery = function(query) {
        var parents;
        var children;

        var splitPoint = query.search("children(\s|:|$)");
        if (splitPoint == -1) {
            parents = query;
            children = "";
        }
        else {
            parents = query.substring(0, splitPoint);
            children = query.substring(splitPoint);
        }

        return {parents: parents, children: children};
    };

    plugin.addReplaceSortOrder = function(query, sort) {
        var rex = /(\s|^)sortOrder:\w+/gi;
        if (query.match(rex)) {
            return query.replace(rex, " sortOrder:" + sort);
        }
        else {
            return query + " sortOrder:" + sort;
        }
    };

    plugin.getSortOrder = function(query) {
        var rex = /(\s|^)sortOrder:(\w+)/i;
        var matches = rex.exec(query);
        if (matches) {
            return matches[2];
        }
        else {
            return null;
        }
    };

}(jQuery));
