<commit_before>/**
 * A client library for sending metrics to statsd.net (https://github.com/lukevenediger/statsd.net/)
 *
 * @constructor
 * @param {string} targetURL the statsd.net http endpoint url
 * @param {string} [rootNamespace=""] a namespace to prefix all outgoing metrics with
 * @param {Number} [pumpIntervalSeconds=10] the time to wait between sending metrics, -1 to disable the pump interval
 * @param {Boolean} [logInternalMetrics=true] switch to enable or disable internal client metrics
 * @param {Number} [maxBufferSize] maximum number of data points to hold in memory between flushes - null for no limit
 * @param {Function} [postFunction] function to post metrics to the stats service
 */
var StatsdnetClient = function (
    targetURL,
    rootNamespace,
    pumpIntervalSeconds,
    logInternalMetrics,
    maxBufferSize,
    postFunction) {

    var me = this;

    if (!targetURL || targetURL === '') {
        throw new Error('Must specify where metrics will be sent to. Parameter: targetURL.');
    }
    rootNamespace = rootNamespace || '';
    pumpIntervalSeconds = pumpIntervalSeconds || 10;
    postFunction = postFunction || postMetricsToServer;

    me._url = targetURL;
    me._rootNamespace = rootNamespace;
    me._postFunction = postFunction;
    me._pumpIntervalEnabled = pumpIntervalSeconds !== -1;
    me._pumpIntervalMS = pumpIntervalSeconds * 1000;
    me._maxBufferSize = maxBufferSize;
    me._logInternalMetrics = (logInternalMetrics || true);
    me._lastRequestLatency = 0;
    me._counts = {};
    me._timings = [];
    me._gauges = {};

    /**
     * Initialise the statsd.net client
     */
    var initialise = function () {
        if (me._pumpIntervalEnabled) {
            pump();
        }
    };

    /**
     * Sends out metrics every x seconds.
     * @returns promise to signal when the send is complete
     */
    var pump = function () {

        var continuePump = function () {
            if (me._pumpIntervalEnabled) {
                setTimeout(pump, me._pumpIntervalMS);
            }
        };

        var payload = buildPayload()
        if (payload.length === 0) {
            // Can't send an empty payload
            continuePump();
            var deferred = jQuery.Deferred();
            deferred.resolve();
            return deferred.promise();
        }

        if (me._logInternalMetrics && me._lastRequestLatency) {
            me.timing('jsclient.post', me._lastRequestLatency);
        }
        var requestStart = new Date().getTime();
        if (me._maxBufferSize && payload.length > me._maxBufferSize) {
            payload.splice(0, payload.length - me._maxBufferSize);
        }
        me._counts = {};
        me._timings = [];
        me._gauges = {};

        // Send the data on its way
        return me._postFunction(me._url, { metrics: payload.join(',') })
            .then(
                function success() {
                    me._lastRequestLatency = new Date().getTime() - requestStart;
                    continuePump();
                },
                function failure() {
                    // eat it
                }
            );
    };

    /**
     * Builds the payload from the counts, timings and gauges
     * @returns {Array<string>} a list of metrics
     */
    var buildPayload = function () {
        var payload = [];
        for (var name in me._counts) {
            payload.push(me._rootNamespace + '.' + name + ':' + me._counts[name] + '|c');
        }
        for (var index = 0; index < me._timings.length; index++) {
            payload.push(me._rootNamespace + '.' + me._timings[index][0] + ':' + me._timings[index][1] + '|ms');
        }
        for (var name in me._gauges) {
            payload.push(me._rootNamespace + '.' + name + ':' + me._gauges[name] + '|g');
        }
        return payload
    };

    /**
     * Posts a batch of metrics off to the statsd.net server
     * @param {String} url
     * @param {Object} payload
     * @returns {Promise}
     */
    var postMetricsToServer = function (url, payload) {
        return jQuery.post(url, payload);
    };

    /**
     * Log a latency in milliseconds
     *
     * @param {string} name the name of this measurement
     * @param {Number} milliseconds the time in milliseconds
     */
    me.timing = function (name, milliseconds) {
        me._timings.push([name, milliseconds]);
    };

    /**
     * Log a count
     *
     * @param {string} name the name of this measurement
     * @param {Number} value the value
     */
    me.count = function (name, value) {
        value = value || 1;
        me._counts[name] = me._counts.hasOwnProperty(name) ? me._counts[name] + value : value;
    };

    /**
     * Log a gauge
     *
     * @param {string} name the name of this measurement
     * @param {Number} value the value
     */
    me.gauge = function (name, value) {
        me._gauges[name] = value;
    };

    /**
     * Flush the pending metrics to the statsd.net endpoint
     * Use this when you want control over when metrics are sent to the server
     * @returns promise to signal when this is complete
     */
    me.flushMetrics = function () {
        return pump();
    };

    initialise();
};<commit_msg>Moving postMetricsToServer()<commit_after>/**
 * A client library for sending metrics to statsd.net (https://github.com/lukevenediger/statsd.net/)
 *
 * @constructor
 * @param {string} targetURL the statsd.net http endpoint url
 * @param {string} [rootNamespace=""] a namespace to prefix all outgoing metrics with
 * @param {Number} [pumpIntervalSeconds=10] the time to wait between sending metrics, -1 to disable the pump interval
 * @param {Boolean} [logInternalMetrics=true] switch to enable or disable internal client metrics
 * @param {Number} [maxBufferSize] maximum number of data points to hold in memory between flushes - null for no limit
 * @param {Function} [postFunction] function to post metrics to the stats service
 */
var StatsdnetClient = function (
    targetURL,
    rootNamespace,
    pumpIntervalSeconds,
    logInternalMetrics,
    maxBufferSize,
    postFunction) {

    var me = this;

    if (!targetURL || targetURL === '') {
        throw new Error('Must specify where metrics will be sent to. Parameter: targetURL.');
    }

    /**
     * Posts a batch of metrics off to the statsd.net server
     * @param {String} url
     * @param {Object} payload
     * @returns {Promise}
     */
    var postMetricsToServer = function (url, payload) {
        return jQuery.post(url, payload);
    };

    rootNamespace = rootNamespace || '';
    pumpIntervalSeconds = pumpIntervalSeconds || 10;
    postFunction = postFunction || postMetricsToServer;

    me._url = targetURL;
    me._rootNamespace = rootNamespace;
    me._postFunction = postFunction;
    me._pumpIntervalEnabled = pumpIntervalSeconds !== -1;
    me._pumpIntervalMS = pumpIntervalSeconds * 1000;
    me._maxBufferSize = maxBufferSize;
    me._logInternalMetrics = (logInternalMetrics || true);
    me._lastRequestLatency = 0;
    me._counts = {};
    me._timings = [];
    me._gauges = {};

    /**
     * Initialise the statsd.net client
     */
    var initialise = function () {
        if (me._pumpIntervalEnabled) {
            pump();
        }
    };

    /**
     * Sends out metrics every x seconds.
     * @returns promise to signal when the send is complete
     */
    var pump = function () {

        var continuePump = function () {
            if (me._pumpIntervalEnabled) {
                setTimeout(pump, me._pumpIntervalMS);
            }
        };

        var payload = buildPayload()
        if (payload.length === 0) {
            // Can't send an empty payload
            continuePump();
            var deferred = jQuery.Deferred();
            deferred.resolve();
            return deferred.promise();
        }

        if (me._logInternalMetrics && me._lastRequestLatency) {
            me.timing('jsclient.post', me._lastRequestLatency);
        }
        var requestStart = new Date().getTime();
        if (me._maxBufferSize && payload.length > me._maxBufferSize) {
            payload.splice(0, payload.length - me._maxBufferSize);
        }
        me._counts = {};
        me._timings = [];
        me._gauges = {};

        // Send the data on its way
        return me._postFunction(me._url, { metrics: payload.join(',') })
            .then(
                function success() {
                    me._lastRequestLatency = new Date().getTime() - requestStart;
                    continuePump();
                },
                function failure() {
                    // eat it
                }
            );
    };

    /**
     * Builds the payload from the counts, timings and gauges
     * @returns {Array<string>} a list of metrics
     */
    var buildPayload = function () {
        var payload = [];
        for (var name in me._counts) {
            payload.push(me._rootNamespace + '.' + name + ':' + me._counts[name] + '|c');
        }
        for (var index = 0; index < me._timings.length; index++) {
            payload.push(me._rootNamespace + '.' + me._timings[index][0] + ':' + me._timings[index][1] + '|ms');
        }
        for (var name in me._gauges) {
            payload.push(me._rootNamespace + '.' + name + ':' + me._gauges[name] + '|g');
        }
        return payload
    };

    /**
     * Log a latency in milliseconds
     *
     * @param {string} name the name of this measurement
     * @param {Number} milliseconds the time in milliseconds
     */
    me.timing = function (name, milliseconds) {
        me._timings.push([name, milliseconds]);
    };

    /**
     * Log a count
     *
     * @param {string} name the name of this measurement
     * @param {Number} value the value
     */
    me.count = function (name, value) {
        value = value || 1;
        me._counts[name] = me._counts.hasOwnProperty(name) ? me._counts[name] + value : value;
    };

    /**
     * Log a gauge
     *
     * @param {string} name the name of this measurement
     * @param {Number} value the value
     */
    me.gauge = function (name, value) {
        me._gauges[name] = value;
    };

    /**
     * Flush the pending metrics to the statsd.net endpoint
     * Use this when you want control over when metrics are sent to the server
     * @returns promise to signal when this is complete
     */
    me.flushMetrics = function () {
        return pump();
    };

    initialise();
};
<|endoftext|>


<commit_before>// ==UserScript==
// @name        studis-online
// @namespace   studis-online.de
// @include     http://*.studis-online.de/Fragen-Brett/*
// @require     https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js
// @version     1
// @grant       none
// ==/UserScript==

$.noConflict(); // Konflikte mit Beitragseditor vermeiden

var Page = new Page();
var ThreadOverview = new ThreadOverview();
var Thread = new Thread();
var Post = new Post();
var SidePanel = new SidePanel();

$(document).ready(function() {
    embedYoutubeLinks();
    cleanUpThreadOverviewTitle();
    fillPostSubjectIfEmpty();
    keepPrivateMessages();
    removeCurrentNews();
    removeFirstPagingInThreadOverview();
    removeMarkAsReadedLinks();
    removePagingText();
    reducePagingWidth();
    insertLetterToMarkThreadAsRead();
    insertDeleteQuoteButtons();
    scaleImageWidthInThreads();
});

function ThreadOverview() {
    this.markAsReadedLinks = $('a[title~="Punkte)"]');
    this.forumTable = $('.ston-forumtab');
    this.redDotElements = this.forumTable.find("span[title='Neu']");
    this.newCreateThreadButton = function() {
        return $('Neues Thema');
    }
}

function Page() {
    this.pagingElements = $('.ston-f-paging');

    // Ob es sich um die Thread-Übersicht-Seite handelt
    this.isThreadOverview = function() {
        return window.location.pathname === '/Fragen-Brett/list.php';
    };

    // Ob es sich um die Private-Message-(Senden)-Seite handelt
    // FIXME: True auf der PrivateMessageOverview
    this.isPrivateMessage = function() {
        //return $('form[action="http://www.studis-online.de/Fragen-Brett/pm.php"]').length === 1;
        return window.location.pathname === '/Fragen-Brett/pm.php';
    };
}

function Thread() {
    this.textblockElements = $('.ston-f-textblock');
    this.markAsReadedLinks = $('a[title~="Punkte)"]');
    this.firstLevelYoutubeLinks = $('.ston-f-textblock > a[href*="youtube.com/watch?"]');
}

function Post() {
    this.bodyElement = $('#post-body');
    this.subjectInput = $('#phorum_subject');
    this.deleteQuoteButtonWidth = 16;
    this.deleteQuoteButtonHTML = '';
    this.keepPrivateMessageCheckbox = $('input[name="keep"]');

    // Funktion auf allen Quotes ausführen
    this.doForEachQuote = function(forEach) { return this.bodyElement.find('blockquote').each(forEach); };

    // Lösch-Button zu allen Zitaten hinzufügen
    this.addDeleteQuoteButtons = function() {
      this.doForEachQuote(function() {
          var postQuoteElement = $(this);
          Post.addDeleteQuoteButton(postQuoteElement);
      });
    }

    // Lösch-Button zu einem Zitat hinzufügen
    this.addDeleteQuoteButton = function(blockquote) {
       var deleteQuoteElements = blockquote.find('.gston-delete-quote');

       if(deleteQuoteElements.length === 0) {
          var position = blockquote.offset().left - this.bodyElement.offset().left + blockquote.innerWidth() - this.deleteQuoteButtonWidth - 5;
          var deleteButtonElement = $(this.deleteQuoteButtonHTML);

          deleteButtonElement.click(function() {
             blockquote.remove();
          });

          blockquote.children().first().prepend(deleteButtonElement);
       }
    };
}

function SidePanel() {
    this.buttons = $('#ston-sp-buttons');
    this.writeButton = this.buttons.find('a[href*="Fragen-Brett/posting.php?"]');
}

// Ersetzt die obere Seitennavigation durch "Neues Thema"-Button
function removeFirstPagingInThreadOverview() { // TODO: function name
    if(Page.isThreadOverview()) {
        var firstPagingElement = Page.pagingElements.first();
        firstPagingElement.before(ThreadOverview.newCreateThreadButton());
        firstPagingElement.remove();
    }
}

// Entfernt die Angabe der Seitenanzahl aus dem Title
// Entfernt den den Text "Unterform" aus der Thread Übersicht
// TODO: Für Threads und Unterordner übernehmen
function cleanUpThreadOverviewTitle() {
    if(Page.isThreadOverview()) {
        var title = $('h1');
        var topTitle = $('.ston-spitz');
        topTitle.remove();
        title.addClass('ston-farbe');
        title.text(title.text().substring(0, title.text().indexOf('[') - 1));
    }
}

// Ersetzt Youtube-Links durch Youtube-Player
function embedYoutubeLinks() {
    Thread.firstLevelYoutubeLinks.each(function() {
        var youtubeLink = $(this);
        var youtubeEmbeddedSource = 'https://youtube.com/embed/' + youtubeLink.attr('href').substring(youtubeLink.attr('href').indexOf('watch?v=') + 8);
        var youtubeEmbeddedIFrame = $('

');
        youtubeLink.before(youtubeEmbeddedIFrame);
        youtubeLink.remove();
    });
}

// Füllt den Betreff eines Posts, falls leer
function fillPostSubjectIfEmpty() {
    if(Post.subjectInput.length > 0) {
       let threadSubject = Post.subjectInput.attr('value');
       Post.subjectInput.parent().find('span').text(threadSubject);
    }
}

// Gesendete Nachrichten speichern
function keepPrivateMessages() {
    if(Page.isPrivateMessage()) {
       Post.keepPrivateMessageCheckbox.click();
    }
}

// Entfernt die aktuellen Meldungen aus der Thread-Übersicht
function removeCurrentNews() {
    // TODO Bundle and remove at once
    var newsElement = $('.ston-klein').filter(function() { return $(this).text().indexOf('Aktuelle Meldungen') === 0});
    newsElement.prev().remove(); //

    newsElement.next().remove(); //

    newsElement.next().remove(); //

    newsElement.remove(); // news
}

// Entfernt den Hinweistext, auf welcher Seite man sich befindet => 'Seite 1 von 24'
function removePagingText() {
    Page.pagingElements.each(function() {
       let pagingCountTextElement = $(this).children().first();
       if(pagingCountTextElement.text().indexOf('Seite') === 0) {
            pagingCountTextElement.remove();
       }
    });
}

// Zeilenumbruch beim Verkleinern des Browsers weiter hinaus zögern
function reducePagingWidth() {
    Page.pagingElements.each(function() {
       $(this).children().last().css('margin-right', '0px');
    });
}

// Entfernt Thema als Gelesen Markieren in Threads
function removeMarkAsReadedLinks() {
    ThreadOverview.markAsReadedLinks.each(function() {
       $(this).remove();
    });

    Thread.markAsReadedLinks.each(function() {
        $(this).remove();
    })
}

// Ersetzt "rote Punkte" (== ungelesen) durch Briefe, welche beim Klick, den Thread als gelesen markieren
function insertLetterToMarkThreadAsRead() {
    if(Page.isThreadOverview()) {
       var redDotElements = ThreadOverview.redDotElements;

       redDotElements.each(function() {
           var redDotElement = $(this);
           var threadLinkElement = redDotElement.parent();
           var unreadedThreadImageElement = $('');
           unreadedThreadImageElement.click(function() {
               var markThreadReadHref = threadLinkElement.attr('href') + ',markthreadread';
               $.ajax({url: markThreadReadHref, success: function(result) {
                  unreadedThreadImageElement.remove();
               }});
           });
           threadLinkElement.before(unreadedThreadImageElement);
           redDotElement.remove();
       });
    } else {
       console.warn("Es gibt mehr als eine Threadübersicht.");
    }
}

// Button zum Löschen von Zitaten
function insertDeleteQuoteButtons() {
    Post.addDeleteQuoteButtons();
    Post.bodyElement.bind("DOMSubtreeModified", function() {
       Post.addDeleteQuoteButtons();
    })
}

// Breite der Bilder in Beiträgen an die Fenstergröße anpassen
// .ston-f-textblock img { max-width: 100%};
function scaleImageWidthInThreads() {
    var images = Thread.textblockElements.find('img');

    images.each(function() {
        $(this).css('max-width', '100%');
    });
}
<commit_msg>Thread overview page<commit_after>// ==UserScript==
// @name        studis-online
// @namespace   studis-online.de
// @include     http://*.studis-online.de/Fragen-Brett/*
// @require     https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js
// @version     1
// @grant       none
// ==/UserScript==

$.noConflict(); // Konflikte mit Beitragseditor vermeiden

var Page = new Page();
var ThreadOverview = new ThreadOverview();
var Thread = new Thread();
var Post = new Post();
var SidePanel = new SidePanel();

$(document).ready(function() {
    embedYoutubeLinks();
    cleanUpThreadOverviewTitle();
    fillPostSubjectIfEmpty();
    keepPrivateMessages();
    removeCurrentNews();
    removeFirstPagingInThreadOverview();
    removeMarkAsReadedLinks();
    removePagingText();
    reducePagingWidth();
    insertLetterToMarkThreadAsRead();
    insertDeleteQuoteButtons();
    scaleImageWidthInThreads();
});

function ThreadOverview() {
    this.markAsReadedLinks = $('a[title~="Punkte)"]');
    this.forumTable = $('.ston-forumtab');
    this.redDotElements = this.forumTable.find("span[title='Neu']");
    this.newCreateThreadButton = function() {
        return $('

Neues Thema

');
    }
}

function Page() {
    this.pagingElements = $('.ston-f-paging');

    // Ob es sich um die Thread-Übersicht-Seite handelt
    this.isThreadOverview = function() {
        return window.location.pathname === '/Fragen-Brett/list.php';
    };

    // Ob es sich um die Private-Message-(Senden)-Seite handelt
    // FIXME: True auf der PrivateMessageOverview
    this.isPrivateMessage = function() {
        //return $('form[action="http://www.studis-online.de/Fragen-Brett/pm.php"]').length === 1;
        return window.location.pathname === '/Fragen-Brett/pm.php';
    };
}

function Thread() {
    this.textblockElements = $('.ston-f-textblock');
    this.markAsReadedLinks = $('a[title~="Punkte)"]');
    this.firstLevelYoutubeLinks = $('.ston-f-textblock > a[href*="youtube.com/watch?"]');
}

function Post() {
    this.bodyElement = $('#post-body');
    this.subjectInput = $('#phorum_subject');
    this.deleteQuoteButtonWidth = 16;
    this.deleteQuoteButtonHTML = '';
    this.keepPrivateMessageCheckbox = $('input[name="keep"]');

    // Funktion auf allen Quotes ausführen
    this.doForEachQuote = function(forEach) { return this.bodyElement.find('blockquote').each(forEach); };

    // Lösch-Button zu allen Zitaten hinzufügen
    this.addDeleteQuoteButtons = function() {
      this.doForEachQuote(function() {
          var postQuoteElement = $(this);
          Post.addDeleteQuoteButton(postQuoteElement);
      });
    }

    // Lösch-Button zu einem Zitat hinzufügen
    this.addDeleteQuoteButton = function(blockquote) {
       var deleteQuoteElements = blockquote.find('.gston-delete-quote');

       if(deleteQuoteElements.length === 0) {
          var position = blockquote.offset().left - this.bodyElement.offset().left + blockquote.innerWidth() - this.deleteQuoteButtonWidth - 5;
          var deleteButtonElement = $(this.deleteQuoteButtonHTML);

          deleteButtonElement.click(function() {
             blockquote.remove();
          });

          blockquote.children().first().prepend(deleteButtonElement);
       }
    };
}

function SidePanel() {
    this.buttons = $('#ston-sp-buttons');
    this.writeButton = this.buttons.find('a[href*="Fragen-Brett/posting.php?"]');
}

// Ersetzt die obere Seitennavigation durch "Neues Thema"-Button
function removeFirstPagingInThreadOverview() { // TODO: function name
    if(Page.isThreadOverview()) {
        var firstPagingElement = Page.pagingElements.first();
        firstPagingElement.before(ThreadOverview.newCreateThreadButton());
        firstPagingElement.remove();
    }
}

// Entfernt die Angabe der Seitenanzahl aus dem Title
// Entfernt den den Text "Unterform" aus der Thread Übersicht
// TODO: Für Threads und Unterordner übernehmen
function cleanUpThreadOverviewTitle() {
    if(Page.isThreadOverview()) {
        var title = $('h1');
        var topTitle = $('.ston-spitz');
        topTitle.text(title.text().substring(0, title.text().indexOf('[') - 1));
        title.remove();
    }
}

// Ersetzt Youtube-Links durch Youtube-Player
function embedYoutubeLinks() {
    Thread.firstLevelYoutubeLinks.each(function() {
        var youtubeLink = $(this);
        var youtubeEmbeddedSource = 'https://youtube.com/embed/' + youtubeLink.attr('href').substring(youtubeLink.attr('href').indexOf('watch?v=') + 8);
        var youtubeEmbeddedIFrame = $('

');
        youtubeLink.before(youtubeEmbeddedIFrame);
        youtubeLink.remove();
    });
}

// Füllt den Betreff eines Posts, falls leer
function fillPostSubjectIfEmpty() {
    if(Post.subjectInput.length > 0) {
       let threadSubject = Post.subjectInput.attr('value');
       Post.subjectInput.parent().find('span').text(threadSubject);
    }
}

// Gesendete Nachrichten speichern
function keepPrivateMessages() {
    if(Page.isPrivateMessage()) {
       Post.keepPrivateMessageCheckbox.click();
    }
}

// Entfernt die aktuellen Meldungen aus der Thread-Übersicht
function removeCurrentNews() {
    // TODO Bundle and remove at once
    var newsElement = $('.ston-klein').filter(function() { return $(this).text().indexOf('Aktuelle Meldungen') === 0});
    newsElement.prev().remove(); //

    newsElement.next().remove(); //

    newsElement.next().remove(); //

    newsElement.remove(); // news
}

// Entfernt den Hinweistext, auf welcher Seite man sich befindet => 'Seite 1 von 24'
function removePagingText() {
    Page.pagingElements.each(function() {
       let pagingCountTextElement = $(this).children().first();
       if(pagingCountTextElement.text().indexOf('Seite') === 0) {
            pagingCountTextElement.remove();
       }
    });
}

// Zeilenumbruch beim Verkleinern des Browsers weiter hinaus zögern
function reducePagingWidth() {
    Page.pagingElements.each(function() {
       $(this).children().last().css('margin-right', '0px');
    });
}

// Entfernt Thema als Gelesen Markieren in Threads
function removeMarkAsReadedLinks() {
    ThreadOverview.markAsReadedLinks.each(function() {
       $(this).remove();
    });

    Thread.markAsReadedLinks.each(function() {
        $(this).remove();
    })
}

// Ersetzt "rote Punkte" (== ungelesen) durch Briefe, welche beim Klick, den Thread als gelesen markieren
function insertLetterToMarkThreadAsRead() {
    if(Page.isThreadOverview()) {
       var redDotElements = ThreadOverview.redDotElements;

       redDotElements.each(function() {
           var redDotElement = $(this);
           var threadLinkElement = redDotElement.parent();
           var unreadedThreadImageElement = $('');
           unreadedThreadImageElement.click(function() {
               var markThreadReadHref = threadLinkElement.attr('href') + ',markthreadread';
               $.ajax({url: markThreadReadHref, success: function(result) {
                  unreadedThreadImageElement.remove();
               }});
           });
           threadLinkElement.before(unreadedThreadImageElement);
           redDotElement.remove();
       });
    } else {
       console.warn("Es gibt mehr als eine Threadübersicht.");
    }
}

// Button zum Löschen von Zitaten
function insertDeleteQuoteButtons() {
    Post.addDeleteQuoteButtons();
    Post.bodyElement.bind("DOMSubtreeModified", function() {
       Post.addDeleteQuoteButtons();
    })
}

// Breite der Bilder in Beiträgen an die Fenstergröße anpassen
// .ston-f-textblock img { max-width: 100%};
function scaleImageWidthInThreads() {
    var images = Thread.textblockElements.find('img');

    images.each(function() {
        $(this).css('max-width', '100%');
    });
}
<|endoftext|>


<commit_before>/**
* A directive that provides a UI to add key-value pair object.
*/
module.exports = function() {
  return {
    scope: {
      data: '=',
      label: '@',
      tooltipText: '@'
    },
    restrict: 'E',
    template: '
' +
                '{{ label | formioTranslate }}' +
                '
' +
                  '
' +
                    '
' +
                      '{{ "Key" | formioTranslate }}	' +
                      '{{ "Value" | formioTranslate }}	' +
                      '	' +
                    '
' +
                  '
' +
                  '
' +
                    '
' +
                      '<input type="text" class="form-control" ng-model="v.key" placeholder="{{ \'Key\' | formioTranslate }}"/>	' +
                      '<input type="text" class="form-control" ng-model="v.value" placeholder="{{ \'Value\' | formioTranslate }}"/>	' +
                      '<button type="button" class="btn btn-danger btn-xs" ng-click="removeValue($index)" tabindex="-1"></button>	' +
                    '
' +
                  '
' +
                '
' +
                '<button type="button" class="btn" ng-click="addValue()">{{ \'Add Value\' | formioTranslate }}</button>' +
              '
',
    replace: true,
    link: function($scope) {
      $scope.data = $scope.data || {};
      $scope.dataArray = [];
      for (var key in $scope.data) {
        $scope.dataArray.push({
          key: key,
          value: $scope.data[key]
        });
      }

      $scope.addValue = function() {
        $scope.dataArray.push({key: '', value: ''});
      };

      $scope.removeValue = function(index) {
        $scope.dataArray.splice(index, 1);
      };

      if ($scope.dataArray.length === 0) {
        $scope.addValue();
      }

      $scope.$watch('dataArray', function(newValue) {
        $scope.data = {};
        for (var i in newValue) {
          var item = newValue[i];
          $scope.data[item.key] = item.value;
        }
      }, true);
    }
  };
};
<commit_msg>FOR-917: Improved 'objectBuilder' directive.<commit_after>/**
* A directive that provides a UI to add key-value pair object.
*/
module.exports = function() {
  return {
    scope: {
      data: '=',
      label: '@',
      tooltipText: '@'
    },
    restrict: 'E',
    template: '
' +
                '{{ label | formioTranslate }}' +
                '
' +
                  '
' +
                    '
' +
                      '{{ "Key" | formioTranslate }}	' +
                      '{{ "Value" | formioTranslate }}	' +
                      '	' +
                    '
' +
                  '
' +
                  '
' +
                    '
' +
                      '<input type="text" class="form-control" ng-model="v.key" placeholder="{{ \'Key\' | formioTranslate }}"/>	' +
                      '<input type="text" class="form-control" ng-model="v.value" placeholder="{{ \'Value\' | formioTranslate }}"/>	' +
                      '<button type="button" class="btn btn-danger btn-xs" ng-click="removeValue($index)" tabindex="-1"></button>	' +
                    '
' +
                  '
' +
                '
' +
                '<button type="button" class="btn" ng-click="addValue()">{{ \'Add Value\' | formioTranslate }}</button>' +
              '
',
    replace: true,
    link: function($scope) {
      init();

      $scope.addValue = function() {
        $scope.dataArray.push({key: '', value: ''});
      };

      $scope.removeValue = function(index) {
        $scope.dataArray.splice(index, 1);
      };

      if ($scope.dataArray.length === 0) {
        $scope.addValue();
      }

      $scope.$watch('data', init);

      $scope.$watch('dataArray', function(newValue) {
        $scope.data = {};
        for (var i in newValue) {
          var item = newValue[i];
          $scope.data[item.key] = item.value;
        }
      }, true);

      function init() {
        $scope.data = $scope.data || {};
        $scope.dataArray = [];
        for (var key in $scope.data) {
          $scope.dataArray.push({
            key: key,
            value: $scope.data[key]
          });
        }
      }
    }
  };
};
<|endoftext|>


<commit_before>'use strict';

import * as PublicGameStates from './states/public_game.server.controller';
import * as PrivateGameStates from './states/private_game.server.controller';

export default class GameRoom {

    constructor(players, is_public_room, game_id) {
        // Set players prop, return error if not array
        if (Array.isArray(players)) this.players = players;
        else throw 'Attempted to create game without correct players param';
        // Set the game_id generated from the game_rooms controller
        this._id = game_id;
        // Is game public, if not then game is private
        this.is_public_room = is_public_room;
        // Set min and max players
        this.min_players = 3;
        this.max_players = 8;
        // Set to true if judge leaves
        this.no_winner = false;
        this.State = is_public_room ? new PublicGameStates.Establishing(this) : new PrivateGameStates.Establishing(this);
    }

    set CurrState(State) {
        this.State = State;
    }

    get CurrState() {
        return this.State;
    }

    // When a player presses leave game
    playerExits(playerToRemove) {
        // Delete player from players array
        this.players.splice(this.players.indexOf(playerToRemove), 1);

        // If theres not enough players to continue, terminate game
        if (this.players.length < this.min_players) {
            this.CurrState = this.is_public_room ? new PublicGameStates.Terminating(this).state_name : new PrivateGameStates.Terminating(this).state_name;
        }
        // Enough players to keep game open
        else {
            // The judge left the game, no winner can be determined
            // TODO: Flag judge for leaving mid-game!
            if (playerToRemove === this.judge) this.no_winner = true;
        }
    }

}
<commit_msg>changed max players to 7<commit_after>'use strict';

import * as PublicGameStates from './states/public_game.server.controller';
import * as PrivateGameStates from './states/private_game.server.controller';

export default class GameRoom {

    constructor(players, is_public_room, game_id) {
        // Set players prop, return error if not array
        if (Array.isArray(players)) this.players = players;
        else throw 'Attempted to create game without correct players param';
        // Set the game_id generated from the game_rooms controller
        this._id = game_id;
        // Is game public, if not then game is private
        this.is_public_room = is_public_room;
        // Set min and max players
        this.min_players = 3;
        this.max_players = 7;
        // Set to true if judge leaves
        this.no_winner = false;
        this.State = is_public_room ? new PublicGameStates.Establishing(this) : new PrivateGameStates.Establishing(this);
    }

    set CurrState(State) {
        this.State = State;
    }

    get CurrState() {
        return this.State;
    }

    // When a player presses leave game
    playerExits(playerToRemove) {
        // Delete player from players array
        this.players.splice(this.players.indexOf(playerToRemove), 1);

        // If theres not enough players to continue, terminate game
        if (this.players.length < this.min_players) {
            this.CurrState = this.is_public_room ? new PublicGameStates.Terminating(this).state_name : new PrivateGameStates.Terminating(this).state_name;
        }
        // Enough players to keep game open
        else {
            // The judge left the game, no winner can be determined
            // TODO: Flag judge for leaving mid-game!
            if (playerToRemove === this.judge) this.no_winner = true;
        }
    }

}
<|endoftext|>


<commit_before>import moment from 'moment';
import find from 'lodash/find';
import sortBy from 'lodash/sortBy';
import clone from 'lodash/clone';
import tail from 'lodash/tail';
import last from 'lodash/last';
import merge from 'lodash/merge';
import get from 'lodash/get';

import client from '../../common/api/client';
import { RESERVATION_STATE } from '../../constants/ReservationState';

export const combineReservations = (reservations) => {
  if (!reservations || !reservations.length) {
    return [];
  }

  const sorted = sortBy(reservations, 'begin');
  const initialValue = [clone(sorted[0])];

  return tail(sorted).reduce((previous, current) => {
    if (current.begin === last(previous).end) {
      last(previous).end = current.end;
    } else {
      previous.push(clone(current));
    }
    return previous;
  }, initialValue);
};

export const getNextAvailableTime = (reservations, fromMoment = moment()) => {
  const combinedReservations = combineReservations(reservations);
  if (!combinedReservations.length || fromMoment < moment(combinedReservations[0].begin)) {
    return fromMoment;
  }

  const ongoingReservation = find(combinedReservations, reservation => (
    moment(reservation.begin) <= fromMoment && fromMoment < moment(reservation.end)
  ));

  return ongoingReservation ? moment(ongoingReservation.end) : fromMoment;
};

export const getCurrentReservation = (reservations) => {
  const now = moment();
  return find(reservations, (reservation) => {
    return moment(reservation.begin) < now && now < moment(reservation.end);
  });
};

/**
 * Edit existing reservation API helper
 * @param {Object} reservation Original reservation data
 * @param {Object} fields Edit fields object
 * @memberof ManageReservationsPage
 * @returns {Promise}
 */
export const putReservation = (reservation, fields) => {
  return client.put(`reservation/${reservation.id}`, merge(reservation, fields), { include: 'resource_detail' });
};
/**
 * Delete/Cancel reservation
 *
 * @param {Object} reservation
 * @returns {Promise}
 */
export const cancelReservation = (reservation) => {
  return client.delete(`reservation/${reservation.id}`);
};

/**
 * Generate reservation edit URL from reservation data.
 *
 * @param {*} reservation
 * @returns {string} Reservation URL
 */
export const getEditReservationUrl = (reservation) => {
  const {
    begin, end, id, resource
  } = reservation;
  const date = moment(begin).format('YYYY-MM-DD');
  const beginStr = moment(begin).format('HH:mm');
  const endStr = moment(end).format('HH:mm');

  return `/reservation?begin=${beginStr}&date=${date}&end=${endStr}&id=${id || ''}&resource=${resource.id}`;
};

/**
 * Check if current user (logged in user) have
 * permission to modify selected reservation.
 * Reservation which in canceled or denied state can not be changed to something else.
 * @param {Object} reservation
 * @returns {Boolean} False by default
 */
export const canUserModifyReservation = (reservation) => {
  if (get(reservation, 'user_permissions.can_modify', false)
      && reservation.state !== RESERVATION_STATE.CANCELLED) {
    return true;
  }

  return false;
};

/**
 * Check if current user (logged in user) have
 * permission to delete (cancel) selected reservation.
 *
 * @param {Object} reservation
 * @returns {Boolean} False by default
 */
export const canUserCancelReservation = (reservation) => {
  if (get(reservation, 'user_permissions.can_delete', false)
      && reservation.state !== RESERVATION_STATE.CANCELLED) {
    return true;
  }

  return false;
};
<commit_msg>fix docs message to be more precise<commit_after>import moment from 'moment';
import find from 'lodash/find';
import sortBy from 'lodash/sortBy';
import clone from 'lodash/clone';
import tail from 'lodash/tail';
import last from 'lodash/last';
import merge from 'lodash/merge';
import get from 'lodash/get';

import client from '../../common/api/client';
import { RESERVATION_STATE } from '../../constants/ReservationState';

export const combineReservations = (reservations) => {
  if (!reservations || !reservations.length) {
    return [];
  }

  const sorted = sortBy(reservations, 'begin');
  const initialValue = [clone(sorted[0])];

  return tail(sorted).reduce((previous, current) => {
    if (current.begin === last(previous).end) {
      last(previous).end = current.end;
    } else {
      previous.push(clone(current));
    }
    return previous;
  }, initialValue);
};

export const getNextAvailableTime = (reservations, fromMoment = moment()) => {
  const combinedReservations = combineReservations(reservations);
  if (!combinedReservations.length || fromMoment < moment(combinedReservations[0].begin)) {
    return fromMoment;
  }

  const ongoingReservation = find(combinedReservations, reservation => (
    moment(reservation.begin) <= fromMoment && fromMoment < moment(reservation.end)
  ));

  return ongoingReservation ? moment(ongoingReservation.end) : fromMoment;
};

export const getCurrentReservation = (reservations) => {
  const now = moment();
  return find(reservations, (reservation) => {
    return moment(reservation.begin) < now && now < moment(reservation.end);
  });
};

/**
 * Edit existing reservation API helper
 * @param {Object} reservation Original reservation data
 * @param {Object} fields Edit fields object
 * @memberof ManageReservationsPage
 * @returns {Promise}
 */
export const putReservation = (reservation, fields) => {
  return client.put(`reservation/${reservation.id}`, merge(reservation, fields), { include: 'resource_detail' });
};
/**
 * Delete/Cancel reservation
 *
 * @param {Object} reservation
 * @returns {Promise}
 */
export const cancelReservation = (reservation) => {
  return client.delete(`reservation/${reservation.id}`);
};

/**
 * Generate reservation edit URL from reservation data.
 *
 * @param {*} reservation
 * @returns {string} Reservation URL
 */
export const getEditReservationUrl = (reservation) => {
  const {
    begin, end, id, resource
  } = reservation;
  const date = moment(begin).format('YYYY-MM-DD');
  const beginStr = moment(begin).format('HH:mm');
  const endStr = moment(end).format('HH:mm');

  return `/reservation?begin=${beginStr}&date=${date}&end=${endStr}&id=${id || ''}&resource=${resource.id}`;
};

/**
 * Check if current user (logged in user) have
 * permission to modify selected reservation.
 *
 * Reservation which in canceled state can not be changed to something else.
 *
 * @param {Object} reservation
 * @returns {Boolean} False by default
 */
export const canUserModifyReservation = (reservation) => {
  if (get(reservation, 'user_permissions.can_modify', false)
      && reservation.state !== RESERVATION_STATE.CANCELLED) {
    return true;
  }

  return false;
};

/**
 * Check if current user (logged in user) have
 * permission to cancel (delete) selected reservation.
 *
 * Reservation which in canceled state can not be changed to something else.
 *
 * @param {Object} reservation
 * @returns {Boolean} False by default
 */
export const canUserCancelReservation = (reservation) => {
  if (get(reservation, 'user_permissions.can_delete', false)
      && reservation.state !== RESERVATION_STATE.CANCELLED) {
    return true;
  }

  return false;
};
<|endoftext|>


<commit_before>'use strict';

// Deals controller
angular.module('savings').controller('SavingsController', ['$scope', '$timeout', '$stateParams', '$location', '$window', 'Authentication', 'Savings', 'FileUploader',
    function($scope, $timeout, $stateParams,  $location, $window, Authentication, Savings, FileUploader) {

        $scope.authentication = Authentication;
        $scope.user = Authentication.user;
        $scope.savingImageURL = '/modules/users/client/img/profile/saveme-placeholder.png';
        // $scope.user.imageURL  = '/modules/users/client/img/profile/saveme-placeholder.png';
        $scope.imageURL1 = '';
        $scope.hottestsorted = true;
        $scope.newestsorted = true;
        $scope.weekly = true;
        $scope.monthly = false;
        $scope.brandLogo = '/modules/users/client/img/profile/argos-logo.png';
        Savings.query({}, function(resp){
            console.log(resp);
            $scope.savings = resp;
        });

        //$scope.user.imageURL = '';
        $scope.submitFormSaving = function(isValid) {
            $scope.submitted = true;
        };

        $scope.hottest = function() {

            alert(123);

            if($scope.hottestsorted === false){
                $scope.hottestsorted = true;
            }else{
                $scope.hottestsorted = false;
            }

        };

        $scope.timeFrame = function (classNum) {

            alert(classNum);

            if(classNum === 1){
                $scope.weekly = true;
                $scope.monthly = false;
            }else if(classNum === 2){
                $scope.weekly = false;
                $scope.monthly = true;
            }

        };

        $scope.setUserImage = function () {

            $scope.user.imageURL = '/modules/users/client/img/profile/saveme-placeholder.png';

        };

        // Create file uploader instance
        $scope.uploaderProductSaving = new FileUploader({
            url: 'api/savings/picture'
        });

        // Set file uploader image filter
        $scope.uploaderProductSaving.filters.push({
            name: 'imageFilter',
            fn: function (item, options) {
                var type = '|' + item.type.slice(item.type.lastIndexOf('/') + 1) + '|';
                return '|jpg|png|jpeg|bmp|gif|'.indexOf(type) !== -1;
            }
        });

        // Change user profile picture
        $scope.uploadProductPictureSaving = function () {

            // Clear messages
            $scope.success = $scope.error = null;

            // Start upload
            $scope.uploaderProductSaving.uploadAll();

        };

        $scope.$watch('urlimage', function(newVal, oldVal){

            if(newVal !== undefined){
                $scope.savingImageURL = newVal;

            }else{
                $scope.savingImageURL = '/modules/users/client/img/profile/saveme-placeholder.png';
            }

        });

        // Called after the user selected a new picture file
        $scope.uploaderProductSaving.onAfterAddingFile = function (fileItem) {

            if ($window.FileReader) {

                var fileReader = new FileReader();
                fileReader.readAsDataURL(fileItem._file);
                fileReader.onload = function (fileReaderEvent) {
                    $timeout(function () {

                        $scope.savingImageURL = fileReaderEvent.target.result;

                    }, 0);
                };
            }

        };

        // Called after the user has successfully uploaded a new picture
        $scope.uploaderProductSaving.onSuccessItem = function (fileItem, response, status, headers) {

            // Show success message
            $scope.success = true;

            // Populate user object
            $scope.user = Authentication.user = response;

            //// Clear upload buttons
             $scope.cancelProductUploadSaving();

        };

        // Called after the user has failed to uploaded a new picture
        $scope.uploaderProductSaving.onErrorItem = function (fileItem, response, status, headers) {

            alert("Failed." + $scope.user.imageURL);

            // Clear upload buttons
            $scope.cancelProductUploadSaving();

            // Show error message
            $scope.error = response.message;
        };

        // Cancel the upload process
        $scope.cancelProductUploadSaving = function () {

            $scope.uploaderProductSaving.clearQueue();
            $scope.savingImageURL = $scope.user.imageURL;

        };

        // Create new Saving
        $scope.create = function () {
            $scope.error = null;

            var image = '/modules/users/client/img/profile/saveme-placeholder.png';
            if($scope.user.imageURL === '/modules/users/client/img/profile/saveme-placeholder.png'){
                //alert("equal")
                image = $scope.savingImageURL;
            }else{
                //alert("not equal")
                image = $scope.user.imageURL;
                //alert("image " + image)
            }

            //alert($scope.savingImageURL);

            // Create new Saving object
            var saving = new Savings({

                title: this.title,
                details: this.details,
                retailer: this.retailer,
                price: this.price,
                link: this.link,
                image: image,
                urlimage: image,
                category: this.category,
                upVoters : $scope.user

            });

            // Redirect after save
            saving.$save(function (response) {

                alert("1 " + $scope.user.imageURL);
                $scope.user.imageURL = '/modules/users/client/img/profile/saveme-placeholder.png';
                alert("2 " + $scope.user.imageURL);
                $location.path('savings/' + response._id);

                // Clear form fields
                $scope.title = '';
                $scope.details = '';
                $scope.retailer = '';
                $scope.price = '';
                $scope.link = '';
                $scope.image = '';
                $scope.urlimage = '';
                $scope.category = '';

            }, function (errorResponse) {
                $scope.error = errorResponse.data.message;
            });
        };

        // Remove existing Saving
        $scope.remove = function (saving) {
            if (saving) {
                saving.$remove();

                for (var i in $scope.savings) {
                    if ($scope.savings[i] === saving) {
                        $scope.savings.splice(i, 1);
                    }
                }
            } else {
                $scope.saving.$remove(function () {
                    $location.path('savings');
                });
            }
        };

        // Update existing Saving
        $scope.update = function() {

            var saving = $scope.saving;

            alert($scope.saving);

            saving.$update(function() {
                $location.path('savings/' + saving._id);
            }, function(errorResponse) {
                $scope.error = errorResponse.data.message;
            });

        };

        // Find a list of Savings
        $scope.find = function () {
            $scope.savings = Savings.query();
        };

        // Find existing Saving
        $scope.findOne = function () {
            $scope.saving = Savings.get({
                savingId: $stateParams.savingId
            });
        };

        // Upvote if user hasnt upvoted already

        $scope.upVoteHome = function(saving) {

            var hasVoted = saving.upVoters.filter(function (voter) {
                    return voter.ref === $scope.loggedInUser;
                }).length > 0;

            // If a downvote exists remove it , else do nothing

            if (!hasVoted) {

                saving.votes++;
                saving.votesreal++;
                //alert(saving.votes);
                saving.upVoters.push($scope.user);

            }

            // Check if there is a downVote to remove

            var hasVoted3 = saving.downVoters.filter(function (voter) {
                    return voter.ref === $scope.loggedInUser;
                }).length > 0;

            if (hasVoted3) {

                for(var i = saving.downVoters.length - 1; i >= 0; i--) {

                    if(saving.downVoters[i] === $scope.user._id) {
                        saving.downVoters.splice(i, 1);
                    }
                }
            }

            saving.$update(function () {
                //$location.path('savings/' + saving._id);
            }, function (errorResponse) {
                // rollback votes on fail also
                $scope.error = errorResponse.data.message;
            });

        };

        $scope.downVoteHome = function(saving) {

            var hasVoted = saving.downVoters.filter(function (voter) {
                    return voter.ref === $scope.loggedInUser;
                }).length > 0;

            // If a upvote exists remove it , else do nothing

            if (!hasVoted) {

                saving.votes--;
                saving.votesreal--;
                saving.downVoters.push($scope.user);

            }

            // Check if there is a upVote to remove

            var hasVoted2 = saving.upVoters.filter(function (voter) {
                    return voter.ref === $scope.loggedInUser;
                }).length > 0;

            if (hasVoted2) {

                for(var i = saving.upVoters.length - 1; i >= 0; i--) {

                    if(saving.upVoters[i] === $scope.user._id) {
                        saving.upVoters.splice(i, 1);
                    }
                }
            }

            saving.$update(function () {
                //$location.path('savings/' + saving._id);
            }, function (errorResponse) {
                // rollback votes on fail also
                $scope.error = errorResponse.data.message;
            });

        };

    }
]);

angular.module('savings').filter('lessThan', function () {
    return function(items, requirement) {
        var filterKey = Object.keys(requirement)[0];
        var filterVal = requirement[filterKey];

        var filtered = [];

        if(filterVal !== undefined && filterVal !== ''){
            angular.forEach(items, function(item) {
                var today = new Date();
                var date = new Date(item.created);
                var diff = today - date;
                diff = diff / (1000*60*60);

                if(diff < filterVal) {
                    filtered.push(item);
                }
            });
            return filtered;
        }

        return items;
    };
});
<commit_msg>Saving update. Weekly/Monthly lists.<commit_after>'use strict';

// Deals controller
angular.module('savings').controller('SavingsController', ['$scope', '$timeout', '$stateParams', '$location', '$window', 'Authentication', 'Savings', 'FileUploader',
    function($scope, $timeout, $stateParams,  $location, $window, Authentication, Savings, FileUploader) {

        $scope.authentication = Authentication;
        $scope.user = Authentication.user;
        $scope.savingImageURL = '/modules/users/client/img/profile/saveme-placeholder.png';
        // $scope.user.imageURL  = '/modules/users/client/img/profile/saveme-placeholder.png';
        $scope.imageURL1 = '';
        $scope.hottestsorted = true;
        $scope.newestsorted = true;
        $scope.weekly = true;
        $scope.monthly = false;
        $scope.brandLogo = '/modules/users/client/img/profile/argos-logo.png';
        Savings.query({}, function(resp){
            console.log(resp);
            $scope.savings = resp;
        });

        //$scope.user.imageURL = '';
        $scope.submitFormSaving = function(isValid) {
            $scope.submitted = true;
        };

        $scope.hottest = function() {

            alert(123);

            if($scope.hottestsorted === false){
                $scope.hottestsorted = true;
            }else{
                $scope.hottestsorted = false;
            }

        };

        $scope.timeFrame = function (classNum) {

            if(classNum === 1){
                $scope.weekly = true;
                $scope.monthly = false;
            }else if(classNum === 2){
                $scope.weekly = false;
                $scope.monthly = true;
            }

        };

        $scope.setUserImage = function () {

            $scope.user.imageURL = '/modules/users/client/img/profile/saveme-placeholder.png';

        };

        // Create file uploader instance
        $scope.uploaderProductSaving = new FileUploader({
            url: 'api/savings/picture'
        });

        // Set file uploader image filter
        $scope.uploaderProductSaving.filters.push({
            name: 'imageFilter',
            fn: function (item, options) {
                var type = '|' + item.type.slice(item.type.lastIndexOf('/') + 1) + '|';
                return '|jpg|png|jpeg|bmp|gif|'.indexOf(type) !== -1;
            }
        });

        // Change user profile picture
        $scope.uploadProductPictureSaving = function () {

            // Clear messages
            $scope.success = $scope.error = null;

            // Start upload
            $scope.uploaderProductSaving.uploadAll();

        };

        $scope.$watch('urlimage', function(newVal, oldVal){

            if(newVal !== undefined){
                $scope.savingImageURL = newVal;

            }else{
                $scope.savingImageURL = '/modules/users/client/img/profile/saveme-placeholder.png';
            }

        });

        // Called after the user selected a new picture file
        $scope.uploaderProductSaving.onAfterAddingFile = function (fileItem) {

            if ($window.FileReader) {

                var fileReader = new FileReader();
                fileReader.readAsDataURL(fileItem._file);
                fileReader.onload = function (fileReaderEvent) {
                    $timeout(function () {

                        $scope.savingImageURL = fileReaderEvent.target.result;

                    }, 0);
                };
            }

        };

        // Called after the user has successfully uploaded a new picture
        $scope.uploaderProductSaving.onSuccessItem = function (fileItem, response, status, headers) {

            // Show success message
            $scope.success = true;

            // Populate user object
            $scope.user = Authentication.user = response;

            //// Clear upload buttons
             $scope.cancelProductUploadSaving();

        };

        // Called after the user has failed to uploaded a new picture
        $scope.uploaderProductSaving.onErrorItem = function (fileItem, response, status, headers) {

            alert("Failed." + $scope.user.imageURL);

            // Clear upload buttons
            $scope.cancelProductUploadSaving();

            // Show error message
            $scope.error = response.message;
        };

        // Cancel the upload process
        $scope.cancelProductUploadSaving = function () {

            $scope.uploaderProductSaving.clearQueue();
            $scope.savingImageURL = $scope.user.imageURL;

        };

        // Create new Saving
        $scope.create = function () {
            $scope.error = null;

            var image = '/modules/users/client/img/profile/saveme-placeholder.png';
            if($scope.user.imageURL === '/modules/users/client/img/profile/saveme-placeholder.png'){
                //alert("equal")
                image = $scope.savingImageURL;
            }else{
                //alert("not equal")
                image = $scope.user.imageURL;
                //alert("image " + image)
            }

            //alert($scope.savingImageURL);

            // Create new Saving object
            var saving = new Savings({

                title: this.title,
                details: this.details,
                retailer: this.retailer,
                price: this.price,
                link: this.link,
                image: image,
                urlimage: image,
                category: this.category,
                upVoters : $scope.user

            });

            // Redirect after save
            saving.$save(function (response) {

                alert("1 " + $scope.user.imageURL);
                $scope.user.imageURL = '/modules/users/client/img/profile/saveme-placeholder.png';
                alert("2 " + $scope.user.imageURL);
                $location.path('savings/' + response._id);

                // Clear form fields
                $scope.title = '';
                $scope.details = '';
                $scope.retailer = '';
                $scope.price = '';
                $scope.link = '';
                $scope.image = '';
                $scope.urlimage = '';
                $scope.category = '';

            }, function (errorResponse) {
                $scope.error = errorResponse.data.message;
            });
        };

        // Remove existing Saving
        $scope.remove = function (saving) {
            if (saving) {
                saving.$remove();

                for (var i in $scope.savings) {
                    if ($scope.savings[i] === saving) {
                        $scope.savings.splice(i, 1);
                    }
                }
            } else {
                $scope.saving.$remove(function () {
                    $location.path('savings');
                });
            }
        };

        // Update existing Saving
        $scope.update = function() {

            var saving = $scope.saving;

            alert($scope.saving);

            saving.$update(function() {
                $location.path('savings/' + saving._id);
            }, function(errorResponse) {
                $scope.error = errorResponse.data.message;
            });

        };

        // Find a list of Savings
        $scope.find = function () {
            $scope.savings = Savings.query();
        };

        // Find existing Saving
        $scope.findOne = function () {
            $scope.saving = Savings.get({
                savingId: $stateParams.savingId
            });
        };

        // Upvote if user hasnt upvoted already

        $scope.upVoteHome = function(saving) {

            var hasVoted = saving.upVoters.filter(function (voter) {
                    return voter.ref === $scope.loggedInUser;
                }).length > 0;

            // If a downvote exists remove it , else do nothing

            if (!hasVoted) {

                saving.votes++;
                saving.votesreal++;
                //alert(saving.votes);
                saving.upVoters.push($scope.user);

            }

            // Check if there is a downVote to remove

            var hasVoted3 = saving.downVoters.filter(function (voter) {
                    return voter.ref === $scope.loggedInUser;
                }).length > 0;

            if (hasVoted3) {

                for(var i = saving.downVoters.length - 1; i >= 0; i--) {

                    if(saving.downVoters[i] === $scope.user._id) {
                        saving.downVoters.splice(i, 1);
                    }
                }
            }

            saving.$update(function () {
                //$location.path('savings/' + saving._id);
            }, function (errorResponse) {
                // rollback votes on fail also
                $scope.error = errorResponse.data.message;
            });

        };

        $scope.downVoteHome = function(saving) {

            var hasVoted = saving.downVoters.filter(function (voter) {
                    return voter.ref === $scope.loggedInUser;
                }).length > 0;

            // If a upvote exists remove it , else do nothing

            if (!hasVoted) {

                saving.votes--;
                saving.votesreal--;
                saving.downVoters.push($scope.user);

            }

            // Check if there is a upVote to remove

            var hasVoted2 = saving.upVoters.filter(function (voter) {
                    return voter.ref === $scope.loggedInUser;
                }).length > 0;

            if (hasVoted2) {

                for(var i = saving.upVoters.length - 1; i >= 0; i--) {

                    if(saving.upVoters[i] === $scope.user._id) {
                        saving.upVoters.splice(i, 1);
                    }
                }
            }

            saving.$update(function () {
                //$location.path('savings/' + saving._id);
            }, function (errorResponse) {
                // rollback votes on fail also
                $scope.error = errorResponse.data.message;
            });

        };

    }
]);

angular.module('savings').filter('lessThan', function () {
    return function(items, requirement) {
        var filterKey = Object.keys(requirement)[0];
        var filterVal = requirement[filterKey];

        var filtered = [];

        if(filterVal !== undefined && filterVal !== ''){
            angular.forEach(items, function(item) {
                var today = new Date();
                var date = new Date(item.created);
                var diff = today - date;
                diff = diff / (1000*60*60);

                if(diff < filterVal) {
                    filtered.push(item);
                }
            });
            return filtered;
        }

        return items;
    };
});
<|endoftext|>


<commit_before>'use strict';

// Deals controller
angular.module('savings').controller('SavingsController', ['$scope', '$http', '$timeout', '$stateParams', '$location', '$window', '$state', 'Authentication', 'Savings', 'FileUploader', 'Posts', 'Users',
    function ($scope, $http, $timeout, $stateParams, $location, $window, $state, Authentication, Savings, FileUploader, Posts, Users ) {

        $scope.authentication = Authentication;
        $scope.user = Authentication.user;
        //$scope.orderByField = 'votesreal';
        $scope.savingImageURL = '/modules/users/client/img/profile/saveme-placeholder.png';
        // $scope.user.imageURL  = '/modules/users/client/img/profile/saveme-placeholder.png';
        $scope.imageURL1 = '';
        $scope.hottestsorted = true;
        $scope.newestsorted = true;
        $scope.weekly = true;
        $scope.monthly = false;
        $scope.disablelist = true;
        $scope.usernamevalue = $stateParams.userId;
        $scope.currency = "Euro (€)";
        $scope.filterUserId = '';
        $scope.brandLogo = '/modules/users/client/img/profile/argos-logo.png';
        $scope.isDisabledUp = false;
        $scope.isDisabledDown = false;
        $scope.yesterdaysDate = new Date();
        $scope.yesterdaysDate.setDate($scope.yesterdaysDate.getDate() - 1);
        $scope.yesterdaysDate = $scope.yesterdaysDate.getMonth( ) + 1 +'/'+ $scope.yesterdaysDate.getDate( ) + '/' +$scope.yesterdaysDate.getFullYear( );

        $scope.savingUrl = function(saving){

           $scope.savingLink =  'http://saveme.ie/savings/'+ saving;
            // console.log($scope.savingLink);
            return $scope.savingLink;

        };

        Savings.query({}, function (resp) {
            //console.log(resp);
            $scope.savings = resp;
        });

        //alert($stateParams.username); // Have Username

        //console.log($scope.ourUser);

        //$scope.user.imageURL = '';
        $scope.submitFormSaving = function (isValid) {
            $scope.submitted = true;
        };

        $scope.hottest = function () {

            //alert(123);

            if ($scope.hottestsorted === false) {
                $scope.hottestsorted = true;
            } else {
                $scope.hottestsorted = false;
            }

        };

        $scope.setSort = function (sort) {

            //alert(sort);

            $scope.orderByField = sort;

        };

        $scope.timeFrame = function (classNum) {

            if (classNum === 1) {
                $scope.weekly = true;
                $scope.monthly = false;
            } else if (classNum === 2) {
                $scope.weekly = false;
                $scope.monthly = true;
            }

        };

        $scope.toggleTop = function () {

            //alert("Top");

            if ($scope.top6 === false) {
                $scope.top6 = true;
            } else {
                $scope.top6 = false;
            }

        };

        $scope.setUserImage = function () {

            $scope.user.imageURL = '/modules/users/client/img/profile/saveme-placeholder.png';

        };

        // Create file uploader instance
        $scope.uploaderProductSaving = new FileUploader({
            url: 'api/savings/picture'
        });

        // Set file uploader image filter
        $scope.uploaderProductSaving.filters.push({
            name: 'imageFilter',
            fn: function (item, options) {
                var type = '|' + item.type.slice(item.type.lastIndexOf('/') + 1) + '|';
                return '|jpg|png|jpeg|bmp|gif|'.indexOf(type) !== -1;
            }
        });

        // Change product profile picture
        $scope.uploadProductPictureSaving = function () {

            // Clear messages
            $scope.success = $scope.error = null;

            // Start upload
            $scope.uploaderProductSaving.uploadAll();

        };

        $scope.$watch('urlimage', function (newVal, oldVal) {

            if (newVal !== undefined) {
                $scope.savingImageURL = newVal;

            } else {
                $scope.savingImageURL = '/modules/users/client/img/profile/saveme-placeholder.png';
            }

        });

        $scope.$watch('pricesterling', function (newVal, oldVal) {

            if (newVal !== undefined) {
                $scope.price = (newVal / 70) * 100;

            }

        });

        // Called after the user selected a new picture file
        $scope.uploaderProductSaving.onAfterAddingFile = function (fileItem) {

            if ($window.FileReader) {

                var fileReader = new FileReader();
                fileReader.readAsDataURL(fileItem._file);
                fileReader.onload = function (fileReaderEvent) {
                    $timeout(function () {

                        $scope.savingImageURL = fileReaderEvent.target.result;

                    }, 0);
                };
            }

        };

        // Called after the user has successfully uploaded a new picture
        $scope.uploaderProductSaving.onSuccessItem = function (fileItem, response, status, headers) {

            // Show success message
            $scope.success = true;

            // Populate user object
            $scope.user = Authentication.user = response;

            //// Clear upload buttons
            $scope.cancelProductUploadSaving();

        };

        // Called after the user has failed to uploaded a new picture
        $scope.uploaderProductSaving.onErrorItem = function (fileItem, response, status, headers) {

            //alert("Failed." + $scope.user.imageURL);

            // Clear upload buttons
            $scope.cancelProductUploadSaving();

            // Show error message
            $scope.error = response.message;
        };

        // Cancel the upload process
        $scope.cancelProductUploadSaving = function () {

            $scope.uploaderProductSaving.clearQueue();
            $scope.savingImageURL = $scope.user.imageURL;

        };

        // Create new Saving
        $scope.create = function () {
            $scope.error = null;

            var image = '/modules/users/client/img/profile/saveme-placeholder.png';
            if ($scope.user.imageURL === '/modules/users/client/img/profile/saveme-placeholder.png') {
                //alert("equal")
                image = $scope.savingImageURL;
            } else {
                //alert("not equal")
                image = $scope.user.imageURL;
                //alert("image " + image)
            }

            if (this.currency === 'Sterling (£)') {

                this.price = Math.round(((this.price / 70) * 100) * 100) / 100;
                this.currency = 'Euro (€)';

            }

            var priceRounded = Math.round(this.price * 100) / 100;

            // Create new Saving object
            var saving = new Savings({

                title: this.title,
                details: this.details,
                retailer: this.retailer,
                price: priceRounded,
                link: this.link,
                currency: this.currency,
                userIdString: $scope.authentication.user._id,
                image: image,
                urlimage: image,
                category: this.category,
                upVoters: $scope.user

            });

            // Redirect after save
            saving.$save(function (response) {

                //alert("1 " + $scope.user.imageURL);
                $scope.user.imageURL = '/modules/users/client/img/profile/saveme-placeholder.png';
                //alert("2 " + $scope.user.imageURL);
                $location.path('savings/' + response._id);

                // Clear form fields
                $scope.title = '';
                $scope.details = '';
                $scope.retailer = '';
                $scope.price = '';
                $scope.link = '';
                $scope.image = '';
                $scope.urlimage = '';
                $scope.category = '';
                $scope.currency = '';

            }, function (errorResponse) {
                $scope.error = errorResponse.data.message;
            });
        };

        // Remove existing Saving
        $scope.removeSaving = function (saving) {

            var result = confirm("Are you sure you want to delete?");
            if (result) {

                // Delete the item

                if (saving) {
                    saving.$remove();

                    for (var i in $scope.savings) {
                        if ($scope.savings[i] === saving) {
                            $scope.savings.splice(i, 1);
                        }
                    }
                } else {
                    $scope.saving.$remove(function () {
                        $location.path('/');
                    });
                }
            }

        };

        // Update existing Saving
        $scope.updateSaving = function () {

            var saving = $scope.saving;

            //alert($scope.saving.currency);

            //if($scope.saving.currency === 'Sterling (£)'){
            //
            //    $scope.saving.price = Math.round((($scope.saving.price/70)*100) * 100) / 100 ;
            //    $scope.saving.currency = 'Euro (€)';
            //    alert($scope.saving.currency);
            //
            //}

            if ($scope.saving.currency === 'Sterling (£)') {

                $scope.saving.price = Math.round((($scope.saving.price / 70) * 100) * 100) / 100;
                $scope.saving.currency = 'Euro (€)';

            }

            //alert($scope.saving.currency);

            saving.$update(function () {
                $location.path('savings/' + saving._id);
            }, function (errorResponse) {
                $scope.error = errorResponse.data.message;
            });

        };

        // Find a list of Savings
        $scope.find = function () {
            $scope.savings = Savings.query();
        };

        // Find existing Saving
        $scope.findOne = function () {
            $scope.saving = Savings.get({
                savingId: $stateParams.savingId
            });
        };

        // Upvote if user hasnt upvoted already

        $scope.upVoteHome = function (saving) {

            // check if yesterdays votes have been removed, if not remove 10% of votes
            // Filter out votesTrim for yesterdays date

            var wasRemoved = saving.votesTrim.filter(function (voter) {

                    return saving.votesTrim === $scope.yesterdaysDate;

                }).length > 0;

            if(!wasRemoved){

                if(saving.votesreal > 100){

                    saving.votesreal = saving.votesreal - (saving.votesreal / 10);
                    saving.votesTrim.push($scope.yesterdaysDate);
                    console.log("removed votes");

                }else{
                    saving.votesreal = 100;
                    saving.votesTrim.push($scope.yesterdaysDate);
                    console.log("changed to 100");
                }

            }

            var hasVoted = saving.upVoters.filter(function (voter) {

                    return voter === $scope.user._id;

                }).length > 0;

            // If a downvote exists remove it , else do nothing

            if (!hasVoted) {

                saving.votes++;
                saving.votesreal++;
                saving.upVoters.push($scope.user);

            }

            // Check if there is a downVote to remove

            var hasVoted3 = saving.downVoters.filter(function (voter) {

                    return voter === $scope.user._id;

                }).length > 0;

            if (hasVoted3) {

                for (var i = saving.downVoters.length - 1; i >= 0; i--) {

                    if (saving.downVoters[i] === $scope.user._id) {
                        saving.downVoters.splice(i, 1);
                    }
                }
            }

            saving.$update(function () {
                //$location.path('savings/' + saving._id);
            }, function (errorResponse) {
                // rollback votes on fail also
                $scope.error = errorResponse.data.message;
            });

        };

        $scope.downVoteHome = function (saving) {

            // check if yesterdays votes have been removed, if not remove 10% of votes
            // Filter out votesTrim for yesterdays date

            var wasRemoved = saving.votesTrim.filter(function (voter) {

                    return saving.votesTrim === $scope.yesterdaysDate;

                }).length > 0;

            if(!wasRemoved){

                if(saving.votesreal > 100){

                    saving.votesreal = saving.votesreal - (saving.votesreal / 10);
                    saving.votesTrim.push($scope.yesterdaysDate);
                    console.log("removed votes");

                }else{
                    saving.votesreal = 100;
                    saving.votesTrim.push($scope.yesterdaysDate);
                    console.log("changed to 100");
                }

            }

            var hasVoted = saving.downVoters.filter(function (voter) {

                    return voter === $scope.user._id;

                }).length > 0;

            // If a upvote exists remove it , else do nothing

            if (!hasVoted) {

                saving.votes--;
                saving.votesreal--;
                saving.downVoters.push($scope.user);

            }

            // Check if there is a upVote to remove

            var hasVoted2 = saving.upVoters.filter(function (voter) {

                    return voter === $scope.user._id;

                }).length > 0;

            if (hasVoted2) {

                for (var i = saving.upVoters.length - 1; i >= 0; i--) {

                    if (saving.upVoters[i] === $scope.user._id) {
                        saving.upVoters.splice(i, 1);
                    }
                }
            }

            saving.$update(function () {
                //$location.path('savings/' + saving._id);

            }, function (errorResponse) {
                // rollback votes on fail also
                $scope.error = errorResponse.data.message;
            });

        };

        $scope.disableButtonUp = function(saving) {

            var hasVotedUp = saving.upVoters.filter(function (voter) {

                    return voter === $scope.user._id;

                }).length > 0;

            if(hasVotedUp){
                return true;

            }else{
                return false;
            }

        };

        $scope.disableButtonDown = function(saving) {

            var hasVotedUp = saving.downVoters.filter(function (voter) {

                    return voter === $scope.user._id;

                }).length > 0;

            if(hasVotedUp){
                return true;

            }else{
                return false;
            }

        };

    }
]);

angular.module('savings').filter('lessThan', function () {
    return function (items, requirement) {
        var filterKey = Object.keys(requirement)[0];
        var filterVal = requirement[filterKey];

        var filtered = [];

        if (filterVal !== undefined && filterVal !== '') {
            angular.forEach(items, function (item) {
                var today = new Date();
                var date = new Date(item.created);
                var diff = today - date;
                diff = diff / (1000 * 60 * 60);

                if (diff < filterVal) {
                    filtered.push(item);
                }
            });
            return filtered;
        }

        return items;
    };
});
<commit_msg>Trim Votes.<commit_after>'use strict';

// Deals controller
angular.module('savings').controller('SavingsController', ['$scope', '$http', '$timeout', '$stateParams', '$location', '$window', '$state', 'Authentication', 'Savings', 'FileUploader', 'Posts', 'Users',
    function ($scope, $http, $timeout, $stateParams, $location, $window, $state, Authentication, Savings, FileUploader, Posts, Users ) {

        $scope.authentication = Authentication;
        $scope.user = Authentication.user;
        //$scope.orderByField = 'votesreal';
        $scope.savingImageURL = '/modules/users/client/img/profile/saveme-placeholder.png';
        // $scope.user.imageURL  = '/modules/users/client/img/profile/saveme-placeholder.png';
        $scope.imageURL1 = '';
        $scope.hottestsorted = true;
        $scope.newestsorted = true;
        $scope.weekly = true;
        $scope.monthly = false;
        $scope.disablelist = true;
        $scope.usernamevalue = $stateParams.userId;
        $scope.currency = "Euro (€)";
        $scope.filterUserId = '';
        $scope.brandLogo = '/modules/users/client/img/profile/argos-logo.png';
        $scope.isDisabledUp = false;
        $scope.isDisabledDown = false;
        $scope.yesterdaysDate = new Date();
        $scope.yesterdaysDate.setDate($scope.yesterdaysDate.getDate() - 1);
        $scope.yesterdaysDate = $scope.yesterdaysDate.getMonth( ) + 1 +'/'+ $scope.yesterdaysDate.getDate( ) + '/' +$scope.yesterdaysDate.getFullYear( );

        $scope.savingUrl = function(saving){

           $scope.savingLink =  'http://saveme.ie/savings/'+ saving;
            // console.log($scope.savingLink);
            return $scope.savingLink;

        };

        Savings.query({}, function (resp) {
            //console.log(resp);
            $scope.savings = resp;
        });

        //alert($stateParams.username); // Have Username

        //console.log($scope.ourUser);

        //$scope.user.imageURL = '';
        $scope.submitFormSaving = function (isValid) {
            $scope.submitted = true;
        };

        $scope.hottest = function () {

            //alert(123);

            if ($scope.hottestsorted === false) {
                $scope.hottestsorted = true;
            } else {
                $scope.hottestsorted = false;
            }

        };

        $scope.setSort = function (sort) {

            //alert(sort);

            $scope.orderByField = sort;

        };

        $scope.timeFrame = function (classNum) {

            if (classNum === 1) {
                $scope.weekly = true;
                $scope.monthly = false;
            } else if (classNum === 2) {
                $scope.weekly = false;
                $scope.monthly = true;
            }

        };

        $scope.toggleTop = function () {

            //alert("Top");

            if ($scope.top6 === false) {
                $scope.top6 = true;
            } else {
                $scope.top6 = false;
            }

        };

        $scope.setUserImage = function () {

            $scope.user.imageURL = '/modules/users/client/img/profile/saveme-placeholder.png';

        };

        // Create file uploader instance
        $scope.uploaderProductSaving = new FileUploader({
            url: 'api/savings/picture'
        });

        // Set file uploader image filter
        $scope.uploaderProductSaving.filters.push({
            name: 'imageFilter',
            fn: function (item, options) {
                var type = '|' + item.type.slice(item.type.lastIndexOf('/') + 1) + '|';
                return '|jpg|png|jpeg|bmp|gif|'.indexOf(type) !== -1;
            }
        });

        // Change product profile picture
        $scope.uploadProductPictureSaving = function () {

            // Clear messages
            $scope.success = $scope.error = null;

            // Start upload
            $scope.uploaderProductSaving.uploadAll();

        };

        $scope.$watch('urlimage', function (newVal, oldVal) {

            if (newVal !== undefined) {
                $scope.savingImageURL = newVal;

            } else {
                $scope.savingImageURL = '/modules/users/client/img/profile/saveme-placeholder.png';
            }

        });

        $scope.$watch('pricesterling', function (newVal, oldVal) {

            if (newVal !== undefined) {
                $scope.price = (newVal / 70) * 100;

            }

        });

        // Called after the user selected a new picture file
        $scope.uploaderProductSaving.onAfterAddingFile = function (fileItem) {

            if ($window.FileReader) {

                var fileReader = new FileReader();
                fileReader.readAsDataURL(fileItem._file);
                fileReader.onload = function (fileReaderEvent) {
                    $timeout(function () {

                        $scope.savingImageURL = fileReaderEvent.target.result;

                    }, 0);
                };
            }

        };

        // Called after the user has successfully uploaded a new picture
        $scope.uploaderProductSaving.onSuccessItem = function (fileItem, response, status, headers) {

            // Show success message
            $scope.success = true;

            // Populate user object
            $scope.user = Authentication.user = response;

            //// Clear upload buttons
            $scope.cancelProductUploadSaving();

        };

        // Called after the user has failed to uploaded a new picture
        $scope.uploaderProductSaving.onErrorItem = function (fileItem, response, status, headers) {

            //alert("Failed." + $scope.user.imageURL);

            // Clear upload buttons
            $scope.cancelProductUploadSaving();

            // Show error message
            $scope.error = response.message;
        };

        // Cancel the upload process
        $scope.cancelProductUploadSaving = function () {

            $scope.uploaderProductSaving.clearQueue();
            $scope.savingImageURL = $scope.user.imageURL;

        };

        // Create new Saving
        $scope.create = function () {
            $scope.error = null;

            var image = '/modules/users/client/img/profile/saveme-placeholder.png';
            if ($scope.user.imageURL === '/modules/users/client/img/profile/saveme-placeholder.png') {
                //alert("equal")
                image = $scope.savingImageURL;
            } else {
                //alert("not equal")
                image = $scope.user.imageURL;
                //alert("image " + image)
            }

            if (this.currency === 'Sterling (£)') {

                this.price = Math.round(((this.price / 70) * 100) * 100) / 100;
                this.currency = 'Euro (€)';

            }

            var priceRounded = Math.round(this.price * 100) / 100;

            // Create new Saving object
            var saving = new Savings({

                title: this.title,
                details: this.details,
                retailer: this.retailer,
                price: priceRounded,
                link: this.link,
                currency: this.currency,
                userIdString: $scope.authentication.user._id,
                image: image,
                urlimage: image,
                category: this.category,
                upVoters: $scope.user

            });

            // Redirect after save
            saving.$save(function (response) {

                //alert("1 " + $scope.user.imageURL);
                $scope.user.imageURL = '/modules/users/client/img/profile/saveme-placeholder.png';
                //alert("2 " + $scope.user.imageURL);
                $location.path('savings/' + response._id);

                // Clear form fields
                $scope.title = '';
                $scope.details = '';
                $scope.retailer = '';
                $scope.price = '';
                $scope.link = '';
                $scope.image = '';
                $scope.urlimage = '';
                $scope.category = '';
                $scope.currency = '';

            }, function (errorResponse) {
                $scope.error = errorResponse.data.message;
            });
        };

        // Remove existing Saving
        $scope.removeSaving = function (saving) {

            var result = confirm("Are you sure you want to delete?");
            if (result) {

                // Delete the item

                if (saving) {
                    saving.$remove();

                    for (var i in $scope.savings) {
                        if ($scope.savings[i] === saving) {
                            $scope.savings.splice(i, 1);
                        }
                    }
                } else {
                    $scope.saving.$remove(function () {
                        $location.path('/');
                    });
                }
            }

        };

        // Update existing Saving
        $scope.updateSaving = function () {

            var saving = $scope.saving;

            //alert($scope.saving.currency);

            //if($scope.saving.currency === 'Sterling (£)'){
            //
            //    $scope.saving.price = Math.round((($scope.saving.price/70)*100) * 100) / 100 ;
            //    $scope.saving.currency = 'Euro (€)';
            //    alert($scope.saving.currency);
            //
            //}

            if ($scope.saving.currency === 'Sterling (£)') {

                $scope.saving.price = Math.round((($scope.saving.price / 70) * 100) * 100) / 100;
                $scope.saving.currency = 'Euro (€)';

            }

            //alert($scope.saving.currency);

            saving.$update(function () {
                $location.path('savings/' + saving._id);
            }, function (errorResponse) {
                $scope.error = errorResponse.data.message;
            });

        };

        // Find a list of Savings
        $scope.find = function () {
            $scope.savings = Savings.query();
        };

        // Find existing Saving
        $scope.findOne = function () {
            $scope.saving = Savings.get({
                savingId: $stateParams.savingId
            });
        };

        // Upvote if user hasnt upvoted already

        $scope.upVoteHome = function (saving) {

            // check if yesterdays votes have been removed, if not remove 10% of votes
            // Filter out votesTrim for yesterdays date

            var wasRemoved = saving.votesTrim.filter(function (voter) {

                    return saving.votesTrim.date === $scope.yesterdaysDate;

                }).length > 0;

            if(!wasRemoved){

                if(saving.votesreal > 100){

                    saving.votesreal = saving.votesreal - (saving.votesreal / 10);
                    saving.votesTrim.push($scope.yesterdaysDate);
                    console.log("removed votes");

                }else{
                    saving.votesreal = 100;
                    saving.votesTrim.push($scope.yesterdaysDate);
                    console.log("changed to 100");
                }

            }

            var hasVoted = saving.upVoters.filter(function (voter) {

                    return voter === $scope.user._id;

                }).length > 0;

            // If a downvote exists remove it , else do nothing

            if (!hasVoted) {

                saving.votes++;
                saving.votesreal++;
                saving.upVoters.push($scope.user);

            }

            // Check if there is a downVote to remove

            var hasVoted3 = saving.downVoters.filter(function (voter) {

                    return voter === $scope.user._id;

                }).length > 0;

            if (hasVoted3) {

                for (var i = saving.downVoters.length - 1; i >= 0; i--) {

                    if (saving.downVoters[i] === $scope.user._id) {
                        saving.downVoters.splice(i, 1);
                    }
                }
            }

            saving.$update(function () {
                //$location.path('savings/' + saving._id);
            }, function (errorResponse) {
                // rollback votes on fail also
                $scope.error = errorResponse.data.message;
            });

        };

        $scope.downVoteHome = function (saving) {

            // check if yesterdays votes have been removed, if not remove 10% of votes
            // Filter out votesTrim for yesterdays date

            var wasRemoved = saving.votesTrim.filter(function (voter) {

                    return saving.votesTrim.date === $scope.yesterdaysDate;

                }).length > 0;

            if(!wasRemoved){

                if(saving.votesreal > 100){

                    saving.votesreal = saving.votesreal - (saving.votesreal / 10);
                    saving.votesTrim.push($scope.yesterdaysDate);
                    console.log("removed votes");

                }else{
                    saving.votesreal = 100;
                    saving.votesTrim.push($scope.yesterdaysDate);
                    console.log("changed to 100");
                }

            }

            var hasVoted = saving.downVoters.filter(function (voter) {

                    return voter === $scope.user._id;

                }).length > 0;

            // If a upvote exists remove it , else do nothing

            if (!hasVoted) {

                saving.votes--;
                saving.votesreal--;
                saving.downVoters.push($scope.user);

            }

            // Check if there is a upVote to remove

            var hasVoted2 = saving.upVoters.filter(function (voter) {

                    return voter === $scope.user._id;

                }).length > 0;

            if (hasVoted2) {

                for (var i = saving.upVoters.length - 1; i >= 0; i--) {

                    if (saving.upVoters[i] === $scope.user._id) {
                        saving.upVoters.splice(i, 1);
                    }
                }
            }

            saving.$update(function () {
                //$location.path('savings/' + saving._id);

            }, function (errorResponse) {
                // rollback votes on fail also
                $scope.error = errorResponse.data.message;
            });

        };

        $scope.disableButtonUp = function(saving) {

            var hasVotedUp = saving.upVoters.filter(function (voter) {

                    return voter === $scope.user._id;

                }).length > 0;

            if(hasVotedUp){
                return true;

            }else{
                return false;
            }

        };

        $scope.disableButtonDown = function(saving) {

            var hasVotedUp = saving.downVoters.filter(function (voter) {

                    return voter === $scope.user._id;

                }).length > 0;

            if(hasVotedUp){
                return true;

            }else{
                return false;
            }

        };

    }
]);

angular.module('savings').filter('lessThan', function () {
    return function (items, requirement) {
        var filterKey = Object.keys(requirement)[0];
        var filterVal = requirement[filterKey];

        var filtered = [];

        if (filterVal !== undefined && filterVal !== '') {
            angular.forEach(items, function (item) {
                var today = new Date();
                var date = new Date(item.created);
                var diff = today - date;
                diff = diff / (1000 * 60 * 60);

                if (diff < filterVal) {
                    filtered.push(item);
                }
            });
            return filtered;
        }

        return items;
    };
});
<|endoftext|>