/*jslint browser: true*/
/*globals $, jQuery*/

$(document).ready(function () {
    $('#taglist').click(function (e) {

        var target = $(e.target),
            alphabet = target.parent(),
            tag,
            tagList = [];

        if (target.is('a') && alphabet.is('li.alphabet')) {

            tag = alphabet.next();

            // Toggle all tags next to the clicked alphabet
            // until another alphabet or the end of list.
            while (tag && !tag.hasClass('alphabet') && tag.parent().attr('id') === 'taglist') {
                if (tag.is(':visible')) {
                    tag.hide();
                } else {
                    tag.show();
                }
                tag = tag.next();
            }
            e.preventDefault();
        }
    });

    // Trigger the click for each alphabet that
    // has a checked tag next to it.
    $('#taglist input:checked').each(function () {

        var tag = $(this).closest('li'),
            alphabet = tag.prev();

        // Rewind elements until the alphabet is met.
        while (alphabet && alphabet.parent().attr('id') === 'taglist') {
            if (alphabet.hasClass('alphabet')) {
                break;
            }
            alphabet = alphabet.prev();
        }

        // Trigger the click for the alphabet and set a flag
        // to avoid multiple triggers for the same alphabet.
        if (alphabet && !alphabet.data('click_triggered')) {
            alphabet.data('click_triggered', true).children('a').trigger('click');
        }
    });

    $('#show-all').click(function (e) {

        var showLink = $(this);

        if (showLink.hasClass('show-all-show')) {
            $('#taglist li:hidden').not('li.alphabet').show();
            showLink.html('Piilota kaikki').removeClass('show-all-show');
        } else {
            $('#taglist li:visible').not('li.alphabet').hide();
            showLink.html('Näytä kaikki').addClass('show-all-show');
        }

        e.preventDefault();
    });

    $('#uncheck-selections').click(function (e) {
        $('#taglist input:checked').removeAttr('checked');
        e.preventDefault();
    });

});

