////////////////////////////////////////////////////////////////////////////////////////////////////////////
// quoteit.js
// Copyright 2012 Provenio Software Corporation. All rights reserved.
// http://q.uote.it/
////////////////////////////////////////////////////////////////////////////////////////////////////////////
(function() {

    var tag = '', qid, allquotes = {};

    function supportsAnimation() {
        // Adapted from https://developer.mozilla.org/en/CSS/CSS_animations/Detecting_CSS_animation_support
        var animation = false,
            animationstring = 'animation',
            keyframeprefix = '',
            domPrefixes = 'Webkit Moz O ms Khtml'.split(' '),
            pfx = '',
            elm = $('body').prop('style');

        if (elm.animationName) { animation = true; }

        if (animation === false) {
            for (var i = 0; i < domPrefixes.length; i++) {
                if (elm[domPrefixes[i] + 'AnimationName'] !== undefined) {
                    pfx = domPrefixes[i];
                    animationstring = pfx + 'Animation';
                    keyframeprefix = '-' + pfx.toLowerCase() + '-';
                    animation = true;
                    break;
                }
            }
        }

        return animation;
    }

    function publishToFacebook() {
        FB.ui(
            {
                app_id: '91205066253',
                method: 'feed',
                name: 'A quote from q.uote.it',
                link: 'http://q.uote.it/',
                picture: 'http://q.uote.it/img/' + tag + '.png',
                caption: $('#author').text() + ' said:',
                description: $('#quote').text()
            },
            function(response) {
                if (response && response.post_id)
                    $.post('/rate-quote', { 'qid': qid(), 'score': '5' }, function(data) { });
            }
        );

        return false;
    }

    function setQuote(id) {
        var quotes = allquotes[tag];
        var i = -1, j = 0, k = 0;
        var quote;

        if (!quotes) {
            getQuotes(true);
            return;
        }

        quote = _.find(quotes, function(quote) { i++; return quote.id == id; });
        if (!quote) {
            window.location.hash = '#/';
        }

        // Display tag cloud for quote
        $('#tag-cloud').empty();
        for (j = 0; j < quote.tags.length; j++) {
            if (quote.tags[j] != tag) {
                $('a#' + quote.tags[j]).clone().appendTo('#tag-cloud');
            }
        }

        if (i >= 1) {
            $('#prev-quote').show().prop('href', '/#/' + tag + '/' + quotes[i - 1].id);
        }
        else {
            $('#prev-quote').hide();
        }

        if (i + 1 < quotes.length) {
            $('#next-quote').show().prop('href', '/#/' + tag + '/' + quotes[(i + 1) % quotes.length].id);
        }
        else {
            $('#next-quote').hide();
        }

        // Author
        $("#author a").text(quote.author).prop('href', '/#/' + quote.author);

        // Show the quote    
        $('h2').empty();
        var lines = quote.quote.split("\n");

        for (i = 0; i < lines.length; i++) {
            $('h2').append('<p></p>');

            var words = lines[i].split(' ');

            for (j = 0; j < words.length; j++) {
                var wd = $('<span class="word">' + words[j] + ' </span>');
                wd.css({ '-webkit-animation-delay': String(k) + 'ms', '-moz-animation-delay': String(k) + 'ms', '-ms-animation-delay': String(k) + 'ms' });
                k += 70;

                $('h2 p:last').append(wd);
            }
        }
    }

    function getQuotes(doTrigger) {
        $('body').addClass('show-quote').removeClass('show-cloud');

        $('h1.quote #p2').text(tag).css({ 'color': $('a#' + tag).css('color') });

        var fGot = function() {
            if (doTrigger) {
                $(window).trigger('hashchange');
            }
            else {
                window.location.hash = '#/' + tag + '/' + qid();
            }
        }

        var quotes = allquotes[tag];
        if (!quotes) {
            $.getJSON("/get-quotes?", { tag: tag }, function(quotes) {
                allquotes[tag] = quotes;
                fGot();
            });
        }
        else {
            fGot();
        }

    }

    function glowRandomTag() {
        // Get a random tag
        var $allTags = $('#big-tag-cloud a');
        var $tag = $allTags.eq(Math.floor(Math.random() * $allTags.length));

        $tag.addClass('doglow');

        window.setTimeout(function() {
            $tag.removeClass('doglow');
            glowRandomTag();
        }, 2500);
    }

    function animateTags() {

        var colours = ['#CB201B', '#498BD5', '#9AB920', '#FFA80B', '#3B329B'];
        var tags = _.pluck(TAG_DATA, 'tag');
        var max = _.max(_.pluck(TAG_DATA, 'count'));

        _.each(TAG_DATA, function(t) {

            var k = Math.floor(Math.random() * 500);
            var a = $('<a></a>'), div = $('<div></div>');
            a.prop('id', t.tag).prop('href', '/#/' + t.tag).text(t.tag).css('font-size', String(1 + (t.count / max)) + 'em');
            a.css('color', colours[Math.floor(Math.random() * 5)]);

            if (supportsAnimation()) {
                div.addClass('fall').css({ 'top': String((Math.random() < 0.5 ? -1 : 1) * Math.floor(Math.random() * 150)) + 'px', 'left': String((Math.random() < 0.5 ? -1 : 1) * Math.floor(Math.random() * 150)) + 'px' });
                a.css({ '-webkit-animation-delay': String(k) + 'ms', '-moz-animation-delay': String(k) + 'ms', '-ms-animation-delay': String(k) + 'ms' }).addClass('show');
            }

            $('#big-tag-cloud').append(div.append(a));
        });

        window.setTimeout(glowRandomTag, 2000);
        window.setTimeout(function() { $('.fall, .show').removeClass(); }, 2100);

        $('#quoteBox').css({ 'width': $('#big-tag-cloud').outerWidth(), 'height': $('#big-tag-cloud').outerHeight() });
    }

    $(document).ready(function() {
        animateTags();

        $('#postToFb').click(publishToFacebook);

        $(window).bind('hashchange', function(e) {
            var hash = window.location.hash.match('\\w.+\\w');

            if (hash) {
                hash = hash[0].split('/');
                tag = hash[0];

                if (hash[1]) {
                    qid = function() { return hash[1]; };
                    setQuote(qid());
                }
                else if (tag) {
                    qid = function() { return allquotes[tag][0].id; };
                    getQuotes(false);
                }
            }
            else {
                $('#tag-cloud, #author a, h2').empty();
                $('body').addClass('show-cloud').removeClass('show-quote');
            }
        });

        $(window).trigger('hashchange');
    });

} ());
