jQuery.noConflict();
jQuery(document).ready(function($){

    /* Misc rules & effects {{{1
     * ***********************************************************************/

    $('.check-all').click(function(){
        $(this).parents('table').find('input[type="checkbox"]').each(function(){
            this.checked = !this.checked;
        });
    });

    $('.sortable').tablesorter({
        headers: {
            0: {sorter: false},
            6: {sorter: false},
            7: {sorter: false},
            8: {sorter: false}
        },
        widthFixed: true,
        widgets: ['zebra']
    }).tablesorterPager({container: $(".tablesorterPager"), size: '40'});

    $('#user-alerts .leave-feedback .form-row').each(function(i){
        if (i !== 0) { $(this).hide(); }
        $(this).find('input[value=1]').click(function(){
            $(this).parents('.form-row').next().show();
        });
    });

    /* Polls {{{1
     * ***********************************************************************/

    function showPollResults(data) {
        if (data.success) {
            var t = $('#poll-'+ data.results.id);
            t.load(t.attr('action') +' #content-sidebar .poll-results');
        }
    }

    $('form.poll p.small').click(function(){
        var pid = $(this).parents('form').attr('id');
        var data = {
            success: true,
            results: {
                id: pid.slice(pid.lastIndexOf('-') + 1, pid.length)
            }
        };
        console.dir(data);
        showPollResults(data);
        return false;
    });

    $('form.poll').submit(function(){
        $.ajax({
            dataType: 'json',
            type: $(this).attr('method'),
            url: $(this).attr('action'),
            data: $(this).serialize(),
            success: showPollResults
        });
        return false;
    });

    /* django-voting {{{1
     * ***********************************************************************/

    $('.vote a').click(function() {
        $this = $(this);
        $.ajax({
            dataType: 'json',
            url: $(this).attr('href'),
            type: 'post',
            data: {},
            success: function(data){
                if (data.success) {
                    $this.siblings().hide();
                    $this.after(' Got it!');
                }
            }
        });
        return false;
    });

    /* Alerts {{{1
     * ***********************************************************************/

    $('body.alerts tr.message-info:odd').addClass('odd');

    function mark_as_read(data) {
        if (data.success) {
            $('tr.message-info input[value="'+ data.alert_id +'"]').parent('td').siblings('td.message-snip').removeClass('unread');

            // Change the Central Info Box count display
            $('#central-info-box #alert-alert-count').text($('#alerts-list td.unread').length);
            if (!$('#messages-list td.unread').length) {
                $('#central-info-box #alert-message-count').remove();
            }
        }
    }

    $('body.alerts tr.message').hide();
    $('body.alerts tr.message-info td.message-snip').css('cursor', 'pointer').click(function(){
        $(this).parent().next('tr.message').animate({'opacity': 'toggle'});
        if ($(this).hasClass('unread')) {
            $.ajax({
                type: 'POST',
                dataType: 'json',
                url: $(this).parents('form').attr('action'),
                data: $(this).siblings('td').children('input').attr('name') +'='+ $(this).siblings('td').children('input').val(),
                success: mark_as_read
            });
        }
    });

    /* Credit {{{1
     * ***********************************************************************/

    $('#credits-faq dd:not(.featured)').hide();
    $('#credits-faq dt').css('cursor', 'pointer').click(function(){
        $(this).next('dd').animate({'opacity': 'toggle'});
    });

    /* Set up modal popups {{{1
     * ***********************************************************************/

    // Set default animations for simpleModal
    $.modal.defaults.onClose = function(dialog) {
        dialog.data.fadeOut('slow', function() {
            dialog.container.hide();
            dialog.overlay.fadeOut('slow', function(){ $.modal.close(); });
        });
    };
    $.modal.defaults.onOpen = function(dialog) {
        dialog.overlay.show().click(function(){
            $.modal.impl.close(false);
        }).css('cursor', 'pointer').attr('title', 'Click to close');
        dialog.container.show('fast', function(){ dialog.data.fadeIn('slow'); });
    };

    // Set default action for a successful form submission
    $.fn.ajaxifyForms.success = function(response){
        if (response.results) {
            var results_ul = $('<ul class="results"/>');
            $('div.modal').append(results_ul);
            results_ul.prepend('<h3>Choose the Game to List</h3>');
            for (var i in response.results) {
                results_ul.append('<li><a href="/games/'+ i +'/list/">'+ response.results[i] +'</a></li>');
            };
        } else {
            $('div.modal').html('<h3>'+ response.message +'</h3>').animate({
                'height': '2.5em'
            }, 'slow',
            function(){
                setTimeout(function(){ $.modal.impl.close(false); }, 1000);
            });
        };
    };

    // Add a modal to specified links
    $('.modal a, a.modal, .help-link').css('cursor', 'pointer').click(function(e){
        e.preventDefault();

        $('<div class="modal"/>').load(
            $(this).attr('href') + ' #content > h2, #content > div#content-main',
            null,
            function() {
                $(this).find('form').ajaxifyForms();
                $(this).modal({
                    containerCss: {
                        width: '800px',
                        height: '600px'
                    },
                    dataCss: {
                        overflow: 'auto'
                    }
                });
            }
        );
    });

    // Add modals to video links
    $('.video a, a.video, a[href*=.flv]').css('cursor', 'pointer').click(function(e){
        e.preventDefault();
        $('<div class="modal"/>').flowplayer("/static/swf/flowplayer-3.0.0.swf", {clip: {url: this.href}}).modal({containerCss: {
            textAlign: 'center',
            width: '512px',
            height: '380px'
        }});
    });

    // FAQ {{{1
    $('body.faq dl').hide();
    $('body.faq dl dd').hide();

    $('body.faq h3').click(function(){
        $(this).next('dl').toggle();
    }).css('cursor', 'pointer');

    $('body.faq dl dt').click(function(){
        $('body.faq dl dt').removeClass('active');
        $(this).addClass('active');
        $('#content-main').html('<h3>'+ $(this).html() +'</h3>').append($(this).next('dd').html());
    }).css('cursor', 'pointer');

    // Tabs {{{1

    // $('div.most-whatever').tabs({ cookie: { expires: 30 } });
    $('dl.most-whatever').dltabs();

    // }}}
    // Ajax Search {{{1

    $("#id_game_search-name").autocomplete('/games/', {
        width: '555px',
        dataType: 'json',
        delay: 100,
        minChars: 2,
        selectFirst: false,
        formatItem: function(data){
            return data.text;
        },
        parse: function(data) {
           var rows = new Array();
           for(var i=0; i<data.length; i++){
               rows[i] = { data:data[i], value:data[i].text, result:data[i].url };
           }
           return rows;
        }
    }).result(function(event, item) {
        location.href = item.url;
    });

    // }}}

});
