choflojt / Imdb Smart Score

// ==UserScript==
// @name         Imdb Smart Score
// @namespace    http://danielbond.se/
// @version      1.1
// @description  Normalizes the imdb rating by filtering out 1s and 10s
// @author       ChoFlojT
// @match        http://www.imdb.com/title/*
// @grant        none
// ==/UserScript==

var toggled;

function setCookie(cname, cvalue, exdays) {
    var d = new Date();
    d.setTime(d.getTime() + (exdays*24*60*60*1000));
    var expires = "expires="+ d.toUTCString();
    document.cookie = 'smartrating-' + cname + "=" + cvalue + ";" + expires + ";path=/";
}

function getCookie(cname) {
    var name = 'smartrating-' + cname + "=";
    var decodedCookie = decodeURIComponent(document.cookie);
    var ca = decodedCookie.split(';');
    for(var i = 0; i <ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') {
            c = c.substring(1);
        }
        if (c.indexOf(name) === 0) {
            return c.substring(name.length, c.length);
        }
    }
    return "";
}

function spacefy(num) {
    var reverse = num.toString().split("").reverse().join("");
    var length = reverse.length;
    var result = "";
    for (var i = 0; i < length; i++) {
        if (i > 0 && i % 3 === 0) {
            result += " ";
        }
        result += reverse.substring(i, i + 1);
    }
    return result.split("").reverse().join("");
}

function saveOldRatingAndVotes(element, rating, votes) {
    element.data('old-rating', rating);
    element.data('old-votes', votes);
}

function saveNewRatingAndVotes(element, rating, votes) {
    element.data('new-rating', rating);
    element.data('new-votes', votes);
}

function useOldRatingAndVotes(element) {
    element.find('.ratingValue strong span').text(element.data('old-rating'));
    element.find('a span').text(element.data('old-votes'));
    element.css('filter', '');
}

function useNewRatingAndVotes(element) {
    element.find('.ratingValue strong span').text(element.data('new-rating'));
    element.find('a span').text(element.data('new-votes'));
    element.css('filter', 'hue-rotate(90deg)');
}

(function() {
    'use strict';

        if (!window.location.pathname.endsWith('ratings'))
        {
            var ratingElement = $('.imdbRating');
            saveOldRatingAndVotes(ratingElement, ratingElement.find('.ratingValue strong span').text(), ratingElement.find('a span').text());

            var totalRealVotes = parseInt($('.imdbRating a span').text().replace(/\D/g,''));
            if (getCookie(window.location.pathname) == totalRealVotes) {
                var roundedScoreString = getCookie(window.location.pathname + '-rating');
                var roundedVotes = getCookie(window.location.pathname + '-votes');
                saveNewRatingAndVotes(ratingElement, roundedScoreString, spacefy(roundedVotes));

                if (getCookie(window.location.pathname + '-toggle') == '0') {
                    toggled = false;
                    useOldRatingAndVotes(ratingElement);
                } else {
                    toggled = true;
                    useNewRatingAndVotes(ratingElement);
                }
            } else {
                $('.ratings_wrapper').prepend('<iframe id="smartRatingIframe" style="visibility:hidden;position:absolute;" />');
                $('#smartRatingIframe').prop('src',window.location.href.split('?')[0] + 'ratings');

                $('#smartRatingIframe').load(function () {
                    var totalVotes = 0;
                    var totalScore = 0;
                    var table = $('#smartRatingIframe').contents().find('#tn15content > table:first');
                    var rows = table.find('tr:not(:first)');
                    var numberOneVotes = 0;
                    var numberTenVotes = 0;

                    rows.each(function () {
                        var row = $(this);
                        var votes = parseInt(row.find('td:first').text());
                        var score = parseInt(row.find('td:last').text());
                        if (score == 1) {
                            numberOneVotes = votes;
                        } else if (score == 10) {
                            numberTenVotes = votes;
                        } else {
                            totalVotes += votes;
                            totalScore += votes * score;
                        }
                    });

                    var factor = numberTenVotes / numberOneVotes;
                    numberTenVotes -= numberOneVotes;
                    if (numberTenVotes > 0) {
                        numberTenVotes = parseInt(numberTenVotes * (1 - 1/factor));
                        totalVotes += numberTenVotes;
                        totalScore += numberTenVotes * 10;
                    } else if (numberTenVotes < 0) {
                        numberOneVotes = -parseInt(numberTenVotes * (1 - factor));
                        totalVotes += numberOneVotes;
                        totalScore += numberOneVotes;
                    }

                    var roundedScore = parseFloat(Math.round((totalScore / totalVotes) * 10) / 10).toFixed(1);
                    var roundedScoreString = roundedScore.toString().replace('.', ',');
                    saveNewRatingAndVotes(ratingElement, roundedScoreString, spacefy(totalVotes));

                    var imdbId = window.location.pathname;
                    setCookie(window.location.pathname, totalRealVotes, 365);
                    setCookie(window.location.pathname + '-rating', roundedScoreString, 365);
                    setCookie(window.location.pathname + '-votes', totalVotes, 365);

                    if (getCookie(window.location.pathname + '-toggle') == '0') {
                        toggled = false;
                        useOldRatingAndVotes(ratingElement);
                    } else {
                        toggled = true;
                        useNewRatingAndVotes(ratingElement);
                    }
                });
            }

            ratingElement.css('cursor', 'pointer');
            ratingElement.prop('title', 'Toggle Smart Rating');
            ratingElement.find('a').click(function (e) {
                e.stopPropagation();
            });
            ratingElement.click(function () {
                if (toggled) {
                    toggled = false;
                    useOldRatingAndVotes(ratingElement);
                    setCookie(window.location.pathname + '-toggle', '0', 365);
                } else {
                    toggled = true;
                    useNewRatingAndVotes(ratingElement);
                    setCookie(window.location.pathname + '-toggle', '1', 365);
                }
            });
        }
})();