var PreviewPlayer = (function(opts) {

    var self = this;

    this.currentId = false;

    var defaultOpts = {
        'width'        : 350,
        'height'       : 18,
        'volume'       : 30,
        'showstop'     : 1,
        'showvolume'   : 1,
        'autoplay'     : 1,
        'buttonwidth'  : 30,
        'sliderwidth'  : 25,
        'volumewidth'  : 40,
        'volumeheight' : 8,
        'loadingcolor' : 'c7ffff',
        'bgcolor1'     : 'a1a1a1',
        'bgcolor2'     : '424242',
        'name'         : '/assets/swf/player_mp3_maxi.swf'
    };

    this.opts = $.extend(defaultOpts, opts);

    this.init = function(id, url) {

        this.id = id;
        this.url = url;

        if (!player.currentId) {
            
            player.currentId = id;
            this._createComponent();
        }
        else {

            if (player.currentId == id) {
                return false;
            }
            else {
                this._destroy(this.currentId);
                player.currentId = id;
                this._createComponent();
            }
        }
    };

    this.goNextTrack = function() {

        var urlsList = $('a.play').get();
        var urlsNum = urlsList.length;

        for (var i = 0; i < urlsNum; i++) {

            if (this.currentId == urlsList[i].id && i != urlsNum - 1) {
                var nextNode = urlsList[i + 1];
                this.init(nextNode.id,  nextNode.href);
                return;
            }
        }
        
        var currentPage = $('#current-page');
        var nextPage = currentPage.next('a.page');

        if (currentPage.length != 0 && nextPage.length != 0) {
            $.cookie('autoload', true, {path: '/', expires: 365});
            window.location = nextPage.attr('href');
        }
    };

    this.setVolume = function(volume) {
        $.cookie('volume', volume, {path: '/', expires: 365});
        player.opts.volume = volume;
    };

    this._createComponent = function() {

        var optsString = $.param(this.opts);

        var playerEmbed  = '<object id="preview-' + this.id + '" type="application/x-shockwave-flash" ';
            playerEmbed += 'data="' + this.opts.name + '" width="' + this.opts.width + '" height="' + this.opts.height + '">';
            playerEmbed += '<param name="movie" value="' + this.opts.name +'" /><param name="FlashVars" ';
            playerEmbed += 'value="' + optsString + '&mp3=' + this.url + '"></object>';
        var playerNode = $(playerEmbed);

        var container = $('#player-place-' + this.id);
        container.append(playerNode);
        playerNode.parent().show();
    };

    this._destroy = function(id) {

        var playerNode = $('#preview-'+ id);
        playerNode.parent().remove();
    };
});
