var player;

$(function() {

    var dialogsOpts = {
        autoOpen: false,
        draggable: false,
        resizable: false,
        modal: true
    };

    var trackinfoDialog = $('#track-info').dialog(dialogsOpts);
    var introModal = $('#intro').dialog(dialogsOpts);

    if (!$.cookie('intro')) {
        $.cookie('intro', true, {path: '/', expires: 365});
        $('#intro').dialog("option", "width", 500);
        $('#intro').dialog("open");
    }

    // Инициализация плеера для предпрослушивания
    player = new PreviewPlayer({'volume' : ($.cookie('volume')) ? $.cookie('volume') : 30});

    // Автопроигрывание первой композиции
    if ($.cookie('autoload')) {
        var firstSongUrl = $('a.play').eq(0);
        $.cookie('autoload', null);
        player.init(firstSongUrl.attr('id'), firstSongUrl.attr('href'));
    }

    (function() {
        // Расчет рейтинга
        var maxRate = 0;

        $('div.ratio').each(function() {
            if ($(this).attr('title') > maxRate) {
                maxRate = $(this).attr('title');
            }
        });

        var onePercent = Math.floor(100 / maxRate);

        $('div.ratio').each(function() {
            var percent = Math.ceil($(this).attr('title') * onePercent);
            var backgroundPos = 100 - percent;
            $(this).css('background-position', backgroundPos + '% 50%');
        });
    })();

    // Сортировка для столбцов таблицы
    $('#search-results').tablesorter({
        widgets: ["zebra"],
        widgetZebra: {css : ['dark', 'light']},
        textExtraction: function(node) {
            if ($(node).hasClass('ratio')) {

                var rateLine = $(node).find('div.ratio');
                if (rateLine.length !== 0) {
                    return rateLine.attr('title');
                }
                else {
                    return '';
                }
            }
            else {
                return $(node).text();
            }
        },
        headers: { 0: { sorter: false}, 1: {sorter: false}, 6: {sorter: false} }
    });

    // Биндинг плеера на иконки воспроизвдения
    $('#search-results a.play').click(function() {
        player.init(this.id,  this.href);
        return false;
    });

    // Модальное окно с дополнительной информацией о треке
    $('#search-results a.track-info').click(function(event) {
        var track_id = $(this).attr('id').substr(1);
        $('img', $(this)).attr('src', '/assets/img/ajax-loader.gif');
        $('img', $(this)).bind('ajaxComplete', function() {
            $(this).attr('src', '/assets/img/iconInfo.png');    
        });
        $.getJSON('/ajax/track/getTrackInfo/' + track_id, function(response) {

            if (response.exception) {
                alert('error');
            }
            else {
                $('#track-info').find('p.trackinfo').each(function() {
                    var container = $('span', $(this));
                    var container_id = container.attr('id');
                    container.text(response[container_id]);
                });

                $('#track-info').dialog("open");
                console.log(response);
            }
        });
        event.preventDefault();
        return false;

    });
});