"use strict";

var Page = require("../models/page");

module.exports = function (app) {

    app.get('/tags', function (req, res) {
        var map = function () {
            if (!this.tags) {
                return;
            }

            for (var index in this.tags) {
                if (this.tags[index]) {
                    emit(this.tags[index], 1);
                }
            }
        };

        var reduce = function (previous, current) {
            var count = 0;

            for (var index in current) {
                if (current.hasOwnProperty(index)) {
                    count += current[index];
                }
            }

            return count;
        };

        Page.mapReduce({
            map: map,
            reduce: reduce

        }, function (err, result) {
            if (err) {
                return res.send(500);
            }
            res.render('tags', {
                title: 'All Pages',
                tags: result,
                latest: Page.latest(10),
                recentChanges: Page.recentChanges(10)
            });
        });
    });

    app.get('/tags/:tag', function (req, res) {
        console.dir(req.params.tag);
        Page.find({
            tags: req.params.tag
        }, function (err, result) {
            if (err) {
                res.send(500);
            }

            res.render("tag", {
                title: "Tag: " + req.params.tag,
                pages: result,
                latest: Page.latest(10),
                recentChanges: Page.recentChanges(10)
            });
        });
    });
};

@@ -82,16 +82,17 @@
 app) %7B%0A%0A
+%0A
     app.
@@ -129,572 +129,8 @@
 s) %7B
-%0A        var map = function () %7B%0A            if (!this.tags) %7B%0A                return;%0A            %7D%0A%0A            for (var index in this.tags) %7B%0A                if (this.tags%5Bindex%5D) %7B%0A                    emit(this.tags%5Bindex%5D, 1);%0A                %7D%0A            %7D%0A        %7D;%0A%0A        var reduce = function (previous, current) %7B%0A            var count = 0;%0A%0A            for (var index in current) %7B%0A                if (current.hasOwnProperty(index)) %7B%0A                    count += current%5Bindex%5D;%0A                %7D%0A            %7D%0A%0A            return count;%0A        %7D;
 %0A%0A  
@@ -201,17 +201,16 @@
  reduce%0A
-%0A
         
@@ -1032,8 +1032,421 @@
  %7D);%0A%7D;%0A
+%0Avar map = function () %7B%0A    if (!this.tags) %7B%0A        return;%0A    %7D%0A%0A    for (var index in this.tags) %7B%0A        if (this.tags%5Bindex%5D) %7B%0A            emit(this.tags%5Bindex%5D, 1);%0A        %7D%0A    %7D%0A%7D;%0A%0Avar reduce = function (previous, current) %7B%0A    var count = 0;%0A%0A    for (var index in current) %7B%0A        if (current.hasOwnProperty(index)) %7B%0A            count += current%5Bindex%5D;%0A        %7D%0A    %7D%0A%0A    return count;%0A%7D;%0A

move map and reduce out of exports function