var playListsCount = 1;
var maxPlayListHeight = 396;
// This is Javascript, not PHP!

function js_array_to_php_array (a)
// This converts a javascript array to a string in PHP serialized format.
// This is useful for passing arrays to PHP. On the PHP side you can
// unserialize this string from a cookie or request variable. For example,
// assuming you used javascript to set a cookie called "php_array"
// to the value of a javascript array then you can restore the cookie
// from PHP like this:
//    <?php
//    session_start();
//    $my_array = unserialize(urldecode(stripslashes($_COOKIE['php_array'])));
//    print_r ($my_array);
//    ?>
// This automatically converts both keys and values to strings.
// The return string is not URL escaped, so you must call the
// Javascript "escape()" function before you pass this string to PHP.
{
    var a_php = "";
    var total = 0;
    for (var key in a)
    {
        ++ total;
        a_php = a_php + "s:" +
        String(key).length + ":\"" + String(key) + "\";s:" +
        String(a[key]).length + ":\"" + String(a[key]) + "\";";
    }
    a_php = "a:" + total + ":{" + a_php + "}";
    return a_php;
}


var initSliderList =  function(container, ajaxURL, onAddContent, context, isNotPlayList){
    //replaceTreePicture('.album_songs_list');
    $(container).click(function(){
        var pel = $(this).parent();
        var id = pel.attr('value');
        var contentBlock = pel.next();
        if ($(contentBlock).is(":hidden")){
            var el = this;
            if (isNotPlayList){
                var childs = $(contentBlock).children();
            }else{
                var childs = $(contentBlock).children().eq(0).children();
            }
            if (childs.length){
                $(contentBlock).fadeIn("slow");
                $(this).parent().addClass('active');

            }else if (id){
                $(contentBlock).fadeIn("slow");
                ClassLoader.ShowSmallLoader(contentBlock);
                t = this;
                if (isNotPlayList){

                    $.ajax({
                        type: 'POST',
                        url: ajaxURL,
                        data: {
                            id: id
                        },
                        success: function(data){

                            $(contentBlock).html(data).fadeIn("slow");

                            $(t).parent().addClass('active');

                            if (onAddContent !== undefined){
                                if (typeof isNotPlayList == 'undefined' || !isNotPlayList){
                                    onAddContent.call(context, contentBlock, id);
                                }else{
                                    onAddContent.call(context, contentBlock);
                                }
                            }
                        }
                    });
                }else{
                    $.ajax({
                        type: 'POST',
                        url: ajaxURL,
                        data: {
                            id: id
                        },
                        dataType: 'json',
                        success: function(json){

                            data = json.html;

                            var prev = $(contentBlock).prev();
                            if (json.result){
                                $(contentBlock).prev().find('.count').html('(' + json.count + ')');
                            }
                            $(contentBlock).replaceWith('<div class="unwrap">' + data + '</div>').fadeIn("slow");
                            contentBlock = $(prev).next();

  
                            $(t).parent().addClass('active');

                            if (onAddContent !== undefined){
                                if (typeof isNotPlayList == 'undefined' || !isNotPlayList){
                                    onAddContent.call(context, contentBlock, id);
                                }else{
                                    onAddContent.call(context, contentBlock);
                                }
                            }
                            if (contentBlock.height() > maxPlayListHeight){
                                contentBlock.height(maxPlayListHeight);
                            }
                            contentBlock.jScrollPane({
                                showArrows:true,
                                scrollbarWidth: 15,
                                arrowSize: 16
                            });
                        }
                    });

                }
            }
        }else{
            $(contentBlock).fadeOut("slow");
            $(this).parent().removeClass('active');
        }
    });
}

/**
 * @param integer album_id - id of album for playing
 * @author Vital Leshchyk
 */
var artistPlayThisAlbum = function(idAlbum){
    $.ajax({
        data:{
            idAlbum: idAlbum
        },
        dataType : 'json',
        type: 'POST',
        url: '/Playlist/_AjaxPlayAlbum',
        success:function(data){
            if ('undefined' != typeof data.result && data.result){
                if (data.result == 2 && clientId) {
                    initAKForm('login', function(){
                        artistPlayThisAlbum(idAlbum);
                    } );
                    return true;
                }
                player.playSong(data.idSong, data.idHistory, true);
            }else{
                alert('Не удалось воспроизвести альбом!', 'Ошибка')
            }
        },
        error : function(XMLHttpRequest, textStatus, errorThrown){
            alert('во время воспроизведения альбома произошла ошибка.', 'Ошибка...')
        }
    
    });

    return false;
}

/**
 *
 * @param integer artist_id - id of artist for playing
 * @author Vital Leshchyk
 */
var artistPlayThisArtist = function(idArtist){
    $.ajax({
        data:{
            idArtist: idArtist
        },
        dataType : 'json',
        type: 'POST',
        url: '/Playlist/_AjaxPlayArtist',
        success:function(data){
            if ('undefined' != typeof data.result && data.result){

                if (data.result == 2 && clientId) {
                    initAKForm('login', function(){
                        artistPlayThisArtist(idArtist);
                    } );
                    return true;
                }

                player.playSong(data.idSong, data.idHistory, true);

            }else{
                alert('Не удалось воспроизвести исполнителя!', 'Ошибка')
            }
        },
        error : function(XMLHttpRequest, textStatus, errorThrown){
            alert('во время воспроизведения исполнителя произошла ошибка.', 'Ошибка...')
        }
    });


    return false;
}

//class for sending of content and links and ...

var BuffaSender = function(data){

    if ('undefined' != typeof(data.linkClass)){
        this.linkClass = data.linkClass;
    }else{
        alert('Ошибка. Не передан класс для ссылки');
        return;
    }
    if ('undefined' != typeof(data.ajaxFormURL)){
        this.ajaxFormURL = data.ajaxFormURL;
    }else{
        alert('Ошибка. Не передан URL для получения формы');
        return;
    }

    this.idSended = data.idSended;
/*
  if ('undefined' != typeof(data.idSended)){
    this.idSended = data.idSended;
  }else{
    alert('Ошибка. Не передан идентификатор объекта');
    return;
  }
  */
//return
//this.linkClass = linkClass;

//initialization of a sender
//this.init();
};

BuffaSender.prototype.dialog;
BuffaSender.prototype.linkClass;
BuffaSender.prototype.oldContent;
BuffaSender.prototype.idSended;
BuffaSender.prototype.ajaxFormURL;
//BuffaSender.prototype.ajaxSendURL;

BuffaSender.prototype.init = function(){
    var t = this;
    $('.' + this.linkClass).bind('click', function(){
        t.initDialog();
        t.dialog.dialog('open');
        return false;
    });
};

BuffaSender.prototype.showDialog = function(){
    this.initDialog();
    this.dialog.dialog('open');
}

BuffaSender.prototype.destroyDlg = function(){
    $(this.dialog).dialog('close');
    $(this.dialog).dialog('destroy');
}

BuffaSender.prototype.initDialog = function(){
    this.dialog = $('<div title="Отправить"><div class="contentContainer">Загрузка...</div><div>');
    this.oldContent = $('.contentContainer', this.dialog).html();
    t = this;
    $(this.dialog).dialog({
        bgiframe: true,
        autoOpen: false,
        resizable: false,
        //draggable: false,
        width: 400,
        modal: true,
        buttons: {
            'Отправить': function() {
                $('form', t.dialog).submit();
            },
            'Закрыть': function() {
                $(this).dialog('close');
            }
        },

        close: function() {
            $('.contentContainer', t.dialog).html(t.oldContent);
        },

        open: function(event, ui) {
            //hide send button
            $('button', t.dialog.parent()).eq(0).hide();
            //load form HTML and show send button
            $.post(t.ajaxFormURL,  {
                idSended: t.idSended
            }, function(data){
                if ('undefined' != typeof(data.result) && 'undefined' != typeof(data.content)) {
                    $('.contentContainer', t.dialog).html(data.content);
                    if (data.result =='1') {
                        t.initAjaxForm();
                    }
                    return;
                }
                t.destroyDlg();
            }, 'json');
        }
    });
};

BuffaSender.prototype.initAjaxForm = function(){
    t = this;
    $('button', t.dialog.parent()).eq(0).show();
    $('#superAjaxForm', t.dialog).ajaxForm({
        url: t.ajaxFormURL,
        beforeSubmit: function () {
            $('button', t.dialog.parent()).eq(0).hide();
        },
        success: function(data){
            if ('undefined' != typeof(data.result) && 'undefined' != typeof(data.content)) {
                switch (data.result) {
                    case '0':
                    case '2':
                        $('.contentContainer', t.dialog).html(data.content);
                        return;
                        break;
                    case '1':
                        $('.contentContainer', t.dialog).html(data.content);
                        //init ajax form
                        t.initAjaxForm();
                        return;
                        break;

                }
            }
            t.destroyDlg();
        },
        dataType: 'json'
    });
}

/*BuffaSender.prototype.initDialog = function(){
    this.dialog = $('<div title="Отправить"><div class="contentContainer">Загрузка...</div><div>');
    this.oldContent = $('.contentContainer', this.dialog).html();
    t = this;
    $(this.dialog).dialog({
        bgiframe: true,
        autoOpen: false,
        resizable: false,
        //draggable: false,
        width: 400,
        modal: true,
        buttons: {
            'Отправить': function() {
                var container = $('.contentContainer', t.dialog);
                var values = {};
                $('.ajaxInputField', container).each(function(){
                    values[$(this).attr('name')]  =  $(this).val();
                });

                values.idSended = t.idSended;

                $('.contentContainer', t.dialog).html(t.oldContent);
                $('button', t.dialog.parent()).eq(0).hide();

                $.post(t.ajaxFormURL, values, function(data){
                    $('.contentContainer', t.dialog).html(data.content);
                    if (data.result == 1) {
                    //$('button', t.dialog.parent()).eq(0).hide();
                    } else {
                        $('button', t.dialog.parent()).eq(0).show();
                    }
                }, 'json');

            },
            'Закрыть': function() {
                $(this).dialog('close');
                $(this).dialog('destroy');
            }
        },
    
        close: function() {
            $('.contentContainer', t.dialog).html(t.oldContent);
        },
    
        open: function(event, ui){
            //hide send button
            $('button', t.dialog.parent()).eq(0).hide();
            //load form HTML and show send button
            $.post(t.ajaxFormURL,  {
                idSended: t.idSended
            }, function(data){
                $('.contentContainer', this.dialog).html(data);
                $('button', t.dialog.parent()).eq(0).show();
            }, 'json');
        }
    });
};
*/
var PlayerController = function(){
  
//this.handleDeleteSongs();
}

//==============================================================================
//==============================================================================
PlayerController.prototype.handleBSongAddBtn = function(data){
    var songs = $('.bSongsBlockItem', data);
    var t = this;
    songs.each(function(){
        t.handleBSongItemAddBtn(this);
    });
}

PlayerController.prototype.handleBSongPlayBtn = function(data, idPlayList){
    var songs = $('.bSongsBlockItem', data);
    var t = this;
    songs.each(function(){
        t.handleBSongItemPlayBtn(this, idPlayList);
    });
}

PlayerController.prototype.handleBArtistAddBtn = function(data){
    var artists = $('.bArtistsBlockItem', data);
    var t = this;
    artists.each(function(){
        t.handleBSongArtistItemAddBtn(this);
    });
}

PlayerController.prototype.handleBArtistPlayBtn = function(data, idPlayList){
    var artists = $('.bArtistsBlockItem', data);
    var t = this;
    artists.each(function(){
        t.handleBArtistItemPlayBtn(this, idPlayList);
    });
}
//------------------------------------------------------------------------------
PlayerController.prototype.handleBSongItemAddBtn = function(data){
    var idSong = $(data).attr('value');
    var t = this;
    $('.bSongItemAddBtn', data).click(function(){
        if (!clientId){
            initAKForm('login');
            return true;
        }else{
            t.addSongToPlayList(idSong);
            return false;
        }
    });
}

PlayerController.prototype.handleBSongItemPlayBtn = function(data, idPlayList){
    var idSong = $(data).attr('value');
    var t = this;
    $('.bSongItemPlayBtn', data).click(function(){
        t.setCurrentPlaylist(idPlayList);
        t.playSong(idSong, idPlayList);
        return false;
    });
}

PlayerController.prototype.handleBSongArtistItemAddBtn = function(data){
    var t = this;
    if ('undefined' == typeof data){
        var els = $('.bArtistItemAddBtn');
    }else{
        var els = $('.bArtistItemAddBtn', data);
    }
    els.click(function(){
        var idArtist = $(this).parent().attr('value');
        if (!idArtist){
            alert('Не получен идентификатор артиста', 'Ошибка');
            return;
        }
        if (!clientId){
            initAKForm('login');
            return true;
        }else{
            t.addArtistToPlayList(idArtist);
            return false;
        }
    });
}

PlayerController.prototype.handleBArtistItemPlayBtn = function(data, idPlayList){
    var t = this;
    if ('undefined' == typeof data){
        var els = $('.bArtistItemPlayBtn');
    }else{
        var els = $('.bArtistItemPlayBtn', data);
    }
    els.click(function(){

        var idArtist = $(this).parent().attr('value');
        if (!idArtist){
            alert('Не получен идентификатор артиста', 'Ошибка');
            return;
        }

        artistPlayThisArtist(idArtist);
        return false;

    });
}
//------------------------------------------------------------------------------
PlayerController.prototype.setCurrentPlaylist = function(idPlayList)
{
    if ('undefined' != typeof idPlayList){
        SetCookie('idCurrentPlaylist', idPlayList, 20);
    }
}
//==============================================================================
//==============================================================================

PlayerController.prototype.playSong = function(idSong, idPlayList, skipAddToPlaylist)
{
    if (parseInt(idSong)>0 && !skipAddToPlaylist) {
        this.onStartSong(idSong, function(){
            getFlashMovie('PlaylistBar_flash').callFlashFunc('_parent._playSong', [idSong, idPlayList]);
        });
    } else {
        getFlashMovie('PlaylistBar_flash').callFlashFunc('_parent._playSong', [idSong, idPlayList]);
    }
    return false;
}



PlayerController.prototype.handlePlayAndAddSongAction = function(data, idPlayList){
    $('a[ajaxor]', data).ajaxor();
    this.handlePlayList(data, idPlayList);
    this.handleAddSongToPlayList(data);
}

PlayerController.prototype.handlePlaySongItem = function(data, idPlayList){
    var idSong = $(data).attr('value');
    var t = this;
  
    $('.btnPlay', data).click(function(){
        t.setCurrentPlaylist(idPlayList);
        t.playSong(idSong, idPlayList);
        return false;
    });
  
}

PlayerController.prototype.handlePlayList = function(data, idPlayList){

    var songs = $('.list-track', data);
    var t = this;
    songs.each(function(){
        t.handlePlaySongItem(this, idPlayList);
    });
}

PlayerController.prototype.handleAddSongItemToPlayList = function(data){
    var idSong = $(data).attr('value');
    var t = this;
    $('.btnAddSongToPlayList', data).click(function(){
        if (!clientId){
            initAKForm('login');
            return true;
        }else{
            t.addSongToPlayList(idSong);
            return false;
        }
    });
}

PlayerController.prototype.handleAddSongToPlayList = function(data){
    var songs = $('.list-track', data);
    var t = this;
    songs.each(function(){
        t.handleAddSongItemToPlayList(this);
    
    });
}

PlayerController.prototype.handleAddAlbumToPlayList = function(data){
    var t = this;
    if ('undefined' == typeof data){
        var els = $('.btnAddAlbumToPlayList');
    }else{
        var els = $('.btnAddAlbumToPlayList', data);
    }
    els.click(function(){
        var idAlbum = $(this).parent().attr('value');
        if (!idAlbum){
            alert('Не получен идентификатор альбома', 'Ошибка');
            return;
        }
        if (!clientId){
            initAKForm('login');
            return true;
        }else{
            t.addAlbumToPlayList(idAlbum);
            return false;
        }
    });
}

PlayerController.prototype.handleAddArtistToPlayList = function(data){
    var t = this;
    if ('undefined' == typeof data){
        var els = $('.btnAddArtistToPlayList');
    }else{
        var els = $('.btnAddArtistToPlayList', data);
    }
    els.click(function(){
        var idArtist = $(this).parent().attr('value');
        if (!idArtist){
            alert('Не получен идентификатор артиста', 'Ошибка');
            return;
        }
        if (!clientId){
            initAKForm('login');
            return true;
        }else{
            t.addArtistToPlayList(idArtist);
            return false;
        }
    });
}



PlayerController.prototype.handleAllActions = function(data, idPlayList){
    this.handlePlayList(data, idPlayList);
    this.handleDeleteSongList(data, idPlayList);
    this.handleDragListItems(data, idPlayList);
    this.handleDropListItems(data);
    this.handleAddSongToPlayList(data);
}

PlayerController.prototype.handleStart = function(){
    // for user's play lists (play song)
    var playLists = $('#userPlaylistsBlock .panel');
    var n = playLists.length;

    //correct height for all playlists
    $('.pl .unwrap').each(function(){
        if ($(this).height()>maxPlayListHeight){
            $(this).height(maxPlayListHeight);
        }
    });
  
    $('.pl .unwrap').jScrollPane({
        showArrows:true,
        scrollbarWidth: 15,
        arrowSize: 16
    });
  

    for (var i = 0; i < n; i ++){
        var pList  = playLists.eq(i);
        var idPlayList = pList.attr('value');
        this.handleAllActions(pList.next(), idPlayList);

        this.handleDeletePlayList(pList);
        this.handlePlayPlayList(pList);
        this.handleDrop(pList);


    }
    this.handlePlayListSearch();
    this.handleAddAlbumToPlayList();
    this.handleAddArtistToPlayList();

    //for tops blocks
    var tops = $('.topSomgsBlock');
    var t = this;
    tops.each(function(){
        t.handlePlayList(this);
        t.handleAddSongToPlayList(this);
    });

    //for tops blocks
    var tops = $('.artistAlbumns');
    var t = this;
    tops.each(function(){
        t.handlePlayList(this);
        t.handleAddSongToPlayList(this);
    });

    //==========================================================================
    var songsBlocks = $('.bSongsBlock'); //SONGS PLAY AND ADD
    var t = this;
    songsBlocks.each(function(){
        t.handleBSongPlayBtn(this);
        t.handleBSongAddBtn(this);
    });
    var artistsBlocks = $('.bArtistsBlock'); //SONGS PLAY AND ADD
    var t = this;
    artistsBlocks.each(function(){
        t.handleBArtistPlayBtn(this);
        t.handleBArtistAddBtn(this);
    });
//==========================================================================
//$('.pl .unwrap').css('height', '200px');

}

PlayerController.prototype.playThisPlaylist = function(idPlayList){
    var t = this;
    t.setCurrentPlaylist(idPlayList);
    t.playSong(-1, idPlayList);
}

PlayerController.prototype.handlePlayPlayList = function(pList){
    var idPlayList = pList.attr('value');
    var t = this;
    $('.btnPlayPlayList', pList).click(function(){
        if (clientId) {
            xmlrpc_check_logged(
                //onOk
                function(){
                    t.playThisPlaylist(idPlayList);
                },
                //onFail
                function(){
                    initAKForm('login', function(){
                        t.playThisPlaylist(idPlayList);
                    });
                }
                );
        } else {
            t.playThisPlaylist(idPlayList);
        }
    });
}

PlayerController.prototype.handleDeletePlayList = function(pList){
    var idPlayList = pList.attr('value');

    var t = this;
    $('.btnDeletePlayList', pList).click(function(){
        //get request text from server
        $.post('/Playlist/_AjaxGetDeletePlayListRequest', {
            idPlayList: idPlayList
        }, function(data){
            if (!data){
                alert('При запросе к серверу произошла ошибка. Удаление невозможно.', 'Ошибка!');
                return;
            }
            dlgConfirm.show(data, 'Удаление плейлиста',
                function(){
                    $.post('/Playlist/_AjaxDeletePlayList', {
                        idPlayList: idPlayList
                    }, function(data){
                        if (data && data != '0'){
                            $(pList).next().remove();
                            $(pList).remove();
                            //$(pList).remove();
                            /*
                if ($(pList).parent().attr('id')){
                  $(pList).remove();
                }else{
                  $(pList).parent().remove();
                }
                */
                            //alert('Плейлист удалён успешно', 'Удаление');
                            if ('function' == typeof calculatePlayListsCount){
                                calculatePlayListsCount();
                            }
                        }else{
                            alert('Не удалось удалить плейлист', 'Ошибка');
                        }
                    });
                }
                );
        });
        return false;
    });
}

PlayerController.prototype.handleDeleteSongList = function(data, idPlayList){
    var songs = $('.list-track', data);
    var t = this;
    var reqCount = 0;
    var reloadList = function(el){
    
    };

    songs.each(function(){
        var idSong = $(this).attr('value');
        var tt = this;
        $('.btnDelSongFromPList', this).click(function(){
            //get request text from server
            /*
      //Вариант запроса с подтверждением удаления

      $.post('/Playlists/AjaxGetDeleteSongRequest', {idPlayList: idPlayList, idSong: idSong}, function(data){
        if (!data){
          alert('При запросе к серверу произошла ошибка. Удаление невозможно.', 'Ошибка!');
          return;
        }
        dlgConfirm.show(data, 'Удаление песни из плейлиста',
          function(){
            $.post('/Playlists/AjaxDeleteSong', {idPlayList: idPlayList, idSong: idSong}, function(data){
              if (data && data != '0'){
                $(tt).remove();
                //alert('Песня удалена успешно', 'Удаление');
                t.reloadPlayList(songs.parent().parent().prev());

              }else{
                alert('Не удалось удалить песню из плейлиста', 'Ошибка');
              }
            });
          }
        );
      });
      */
            //Ничего не спрашиваем,  просто удаляем
            /*
      $.post('/Playlists/AjaxDeleteSong', {idPlayList: idPlayList, idSong: idSong}, function(data){
        reqCount --;
        if (data && data != '0'){
          $(tt).remove();
          //alert('Песня удалена успешно', 'Удаление');
           t.reloadPlayList(songs.parent().parent().parent().prev());
        }else{
          alert('Не удалось удалить песню из плейлиста', 'Ошибка');
          t.reloadPlayList(songs.parent().parent().parent().prev());
        }
      });
      */
            if (reqCount >= 4){
                return false;
            }
            $.ajax({
                url: '/Playlist/_AjaxDeleteSong',
                type: 'POST',
                data: {
                    idPlayList: idPlayList,
                    idSong: idSong
                },
                success:function(data){
                    if (data && data != '0'){
                    //$(tt).remove();
                    //alert('Песня удалена успешно', 'Удаление');
                    //t.reloadPlayList(songs.parent().parent().parent().prev(), false, true);
                    }else{
                //alert('Не удалось удалить песню из плейлиста', 'Ошибка');
                //t.reloadPlayList(songs.parent().parent().parent().prev(), false, true);
                }
                },
                complete: function(){
                    reqCount --;
                    if (!reqCount){
                        t.reloadPlayList(songs.parent().parent().parent().prev(), false, true);
                    }
                    ClassLoader.HideSmallLoader();
                }

            });
            $(tt).remove();
            reqCount ++;
            return false;
        });
    });
}

PlayerController.prototype.reloadPlayList = function(contentBlock, noRefresh, noIndikator, callBack){

    var id = contentBlock.attr('value');
    var t = this;
    var prevCount = 0;
    prevCount = contentBlock.next().find('.unwrap .cnt').children().length;
    if (("undefined" == typeof noIndikator) && !noIndikator){
        blockForIndicator = contentBlock.next().find('.unwrap');
        prevCount = blockForIndicator.children().length;
        ClassLoader.ShowSmallLoader(blockForIndicator);
    }

    $.ajax({
        url: '/playlist/_AjaxPlaylistSongs',
        type : 'POST',
        data : {
            id: id
        },
        dataType: 'json',
        success:function(json){
            /*contentBlock = contentBlock.next().find('.unwrap');

			*/
            var prev = contentBlock;
            contentBlock = contentBlock.next();
            //var prev = $(contentBlock).prev();
            data = json.html;

            if (json.result){
                $(contentBlock).prev().find('.count').html('(' + json.count + ')');
            }

            var top = parseInt($('.jScrollPaneDrag', $(contentBlock)).css('top'));
            top = top * $('.cnt', $(contentBlock)).height() / $(contentBlock).height();

            $(contentBlock).visible;

            if ($(contentBlock).is(':visible')){
                $(contentBlock).replaceWith('<div class="unwrap">' + data + '</div>').show();
                contentBlock = $(prev).next();
            }else{
                //$(contentBlock).replaceWith('<div class="unwrap">' + data + '</div>').hide();
                //contentBlock = $(prev).next();
                //contentBlock.hide();
       

                return;
            }
      
  


            if (contentBlock.height() > maxPlayListHeight){
                contentBlock.height(maxPlayListHeight);
            }

            var cont = contentBlock.jScrollPane({
                showArrows:true,
                scrollbarWidth: 15,
                arrowSize: 16
            });

   
            if ('undefined' != typeof cont[0] && 'function' == typeof cont[0].scrollTo && parseInt(top)){
                cont[0].scrollTo(parseInt(top));
            };
            //$('.jScrollPaneDrag', $(contentBlock)).css('top', top);

            //player.handleAllActions(contentBlock, id);
            player.handleAllActions(cont, id);

            if (("undefined" == typeof noRefresh) || !noRefresh){
                //refreshPlaylist(id);

                refreshPlaylistList();
            }

        //player.handleAllActions(data);
        /*
			var a = $(contentBlock).html(data);
			player.handleAllActions(a, id);
			*/
        },
        complete: function(){
            if (("undefined" == typeof noIndikator) && !noIndikator){
                ClassLoader.HideSmallLoader();
            }

            if (("undefined" != typeof callBack) && callBack){
                callBack();
            }

            calculatePlayListsCount();
        }
    });
}

var ii = 0;
PlayerController.prototype.orderArray = new Array();
PlayerController.prototype.orderUpdateListsArray = new Array();

PlayerController.prototype.handleDragListItems = function(data, idPlayList){
  
    //var idPlayList = pList.attr('value');
    var t = this;
    var ttt = this;



    //alert($(pList).parent().html());
    //var twoLists = false;
    var contentBlock = data;
    var reqCount = 0;
    $(data).find('.cnt').sortable({
        items: '.list-track',
        //appendTo: '#userPlaylistsBlock',
        connectWith: "#userPlaylistsBlock .unwrap .cnt",

        helper:'clone',
        appendTo: 'body',
        revert: true,
        //opacity: 0.8,
        cursor: 'move',

        scroll:false,
        zIndex: 6009,
        start:function(event,ui){
            //$(this).draggable('disable');
            ui.helper.css('position', 'absolute').css('zIndex', '9000').addClass('dragged');
        },
        change:function(event,ui){
        //ui.helper.css('position', 'absolute').css('zIndex', '9000').addClass('dragged').css('background-color', '#e3F9C');
        //$('#userPlaylistsBlock').append(ui.helper);

        //ui.helper.css('position', 'absolute').css('zIndex', '9000').addClass('dragged');
        //$('#userPlaylistsBlock').append(ui.helper);



        //$('body').parent().append(ui.helper);
        },
        update: function() {

            var order = $(this).sortable("serialize");

            //generation of a orderArray();
            var arr = $(this).sortable("toArray");
            var oArr = new Array();
            n = arr.length;
            for (var i = 0; i < n; i ++){
                a = arr[i].split('_');
                oArr[i] = a[1];
            }

            t.orderArray[$(this).attr('value')] = oArr;
            t.orderUpdateListsArray[t.orderUpdateListsArray.length] = $(this).parent().parent().parent().children().eq(0);
        //var a = 1;
        },
        receive:function(){

        },
        stop: function(){

            if (ttt.orderArray.length && reqCount < 1){

                n = ttt.orderUpdateListsArray.length;
                for (var i = 0; i < n; i ++){
                    $('.cnt', $(ttt.orderUpdateListsArray[i]).next()).sortable('destroy');
                }

                $.post('/playlist/_AjaxSetSongsOrder', {
                    order: js_array_to_php_array(ttt.orderArray)
                }, function(data){
                    if ('ok' != data){
                        alert(data, 'Ошибка!');
                    }

                    n = ttt.orderUpdateListsArray.length;

                    for (var i = 0; i < n; i ++){
                        //alert(ttt.orderUpdateListsArray[i].html());
                        if (i == n - 1){

                            ttt.reloadPlayList(ttt.orderUpdateListsArray[i], false, true, function(){
                                reqCount = 0;
                            });
                        }else{
                            ttt.reloadPlayList(ttt.orderUpdateListsArray[i], false, true);
                        }
            
                    }
                    //ttt.reloadPlayList($(contentBlock).prev());
                    delete ttt.orderUpdateListsArray;
                    ttt.orderUpdateListsArray = new Array();

                    delete ttt.orderArray;
                    ttt.orderArray = new Array();
                });
                reqCount ++
            }

        //delete ttt.orderArray;
        //ttt.orderArray = new Array();
        }

    }).disableSelection();
/*
  $(pList).next().find('.list-track').draggable({
        cursor: "move",
        revert: true,
        revertDuration: 500,
        distance: 5,
        refreshPositions: true,
        scroll:false,
        snap:true,
        start:function(){
          dragType = 'artist';
          dragId = $(this).attr('value');
          //alert($(this).html());
          //$(this).html($(this).html());
          return false;
        },
        stop:function(){
          dragType = null;
          dragId = null;
          return false;
        }
  });
  */
  

}

PlayerController.prototype.handleDropListItems = function(pList){
    if ('undefined' != typeof pList.prev().attr('value')){
        pList = pList.prev();
    }else{
        pList = pList.parent().prev();
    }
    var t = this;
    var onDrop2 = function(event, ui){
        //idPlayList = $(this).parent().parent().prev().attr('value');
        idPlayList = $(this).parent().parent().parent().prev().attr('value');
        //return;
        switch (dragType){
            case 'artist':{
                player.addToPlayList(idPlayList, 'artist', dragId, function(){
                    t.reloadPlayList(pList, true);
                }, $(this).attr('orderId'));
            //alert('артист добавлен в плейлист', 'Добавление в плейлист')
            }
            break;
            case 'album':{
                player.addToPlayList(idPlayList, 'album', dragId, function(){
                    t.reloadPlayList(pList, true);
                }, $(this).attr('orderId'));
            //alert('альбом добавлен в плейлист', 'Добавление в плейлист')
            }
            break;
            case 'song':{
                //player.addToPlayList(idPlayList, 'song', dragId, function(){
                //            t.reloadPlayList(pList, true);
                //          });
                /*xmlrpc_add_to_playlist(idPlayList, dragId, function(){
            t.reloadPlayList(pList, true);
          }, $(this).attr('orderId'));
          */
                player.addToPlayList(idPlayList, 'song', dragId, function(){
                    t.reloadPlayList(pList, true);
                }, $(this).attr('orderId'));

            //alert('песня добавлена в плейлист', 'Добавление в плейлист')
            }
            break;
            default:{
                //alert('Перетащен неопознанный объект', 'Ошибка')
                }

        }
        dragId = null;
        dragType = null;
    };

    pList.next().find('.list-track').droppable({
        drop: onDrop2,
        addClasses: false,
        hoverClass: 'tstClass'
    });
  
}

PlayerController.prototype.handleDrop = function(pList){
    var idPlayList = pList.attr('value');
    var t = this;
    var onDrop = function(event, ui){
        switch (dragType){
            case 'artist':{
                player.addToPlayList(idPlayList, 'artist', dragId, function(){
                    t.reloadPlayList(pList, true);
                });
            //alert('артист добавлен в плейлист', 'Добавление в плейлист')
            }
            break;
            case 'album':{
                player.addToPlayList(idPlayList, 'album', dragId, function(){
                    t.reloadPlayList(pList, true);
                });
            //alert('альбом добавлен в плейлист', 'Добавление в плейлист')
            }
            break;
            case 'song':{
                /*
          xmlrpc_add_to_playlist(idPlayList, dragId, function(){
            t.reloadPlayList(pList, true);
          });
          */
                player.addToPlayList(idPlayList, 'song', dragId, function(){
                    t.reloadPlayList(pList, true);
                });

            //alert('песня добавлена в плейлист', 'Добавление в плейлист')
            }
            break;
            default:{
                //alert('Перетащен неопознанный объект', 'Ошибка')
                }
        }
        dragId = null;
        dragType = null;
    };


    //pList.droppable('destroy');
    pList.droppable({
        drop: onDrop,
        addClasses: false
    });
    this.handleDropListItems(pList.next());
  
/*$('.btnPlayPlayList', pList).click(function(){
    t.playSong(-1, idPlayList);
  });
  */
}

PlayerController.prototype.onStartSong = function(idSong, onOk){
    $.ajax({
        url: '/playlist/_AjaxPlaySong',
        type : 'POST',
        data : {
            idSong: idSong
        },
        success:function(data){
            if (data == 2) {
                if (clientId) {
                    if ('function' == typeof onOk) {
                        initAKForm('login', function(){
                            onOk(1);
                        } );
                    } else {
                        initAKForm('login');
                    }
                    return true;
                } else {
                    data = 1;
                }
            }
            
            if ('function' == typeof onOk) {
                onOk(data);
            }

        }
    });
}

PlayerController.prototype.handlePlayListSearch = function(){
    var t = this;
    $('#playListSearchButton').bind('click', function(){
        var searchString = $('#searchInput').val();
        t.playListSearch(searchString);
        return false;
    });
  
    $('#playListsSearchFrm input').keydown(function(event){
        if(event.keyCode != 13 || $('li.ac_over').length){
            return true;
        }

        var searchString = $('#searchInput').val();
        t.playListSearch(searchString);
        return false;
    });

    var input = $("#searchInput");
    var width = parseInt(input.width()) + 40;
    input.autocomplete('/search/_AjaxGetSearchHint', {
        width: width,
        matchContains: true,
        formatResult: formatResult,
        selectFirst: false,
        onChange:function(){
            var searchString = $('#searchInput').val();
            t.playListSearch(searchString);
        }
    });
}

PlayerController.prototype.handleResults = function(data, dontReplace){
    var t = this;

    if ('undefined' == dontReplace || !dontReplace){
        $('#pListRightBar').html(data);
    }
    t.handlePlayList($('#pListRightBar'));
    t.handleAddSongToPlayList($('#pListRightBar'));
    handleDragSongs();
    handleDragAlbum();
    handleArtists();
    t.handleAddArtistToPlayList();
    t.handleAddAlbumToPlayList();
    //t.handleAddSongToPlayList();
    $('#pListRightBar .searchAllBlock a').click(function(){
        t.expandSearchResult($(this).attr('href'));
        return false;
    });  
}

PlayerController.prototype.expandSearchResult = function(url){
    var t = this;
    $.ajax({
        type: 'POST',
        url: encodeURI(url)+'&param=2',
        dataType: 'json',
        success: function(data){
            t.handleResults(data.html);
            
            Navigation.getNavigationInfo(0, function(){
                Navigation.initPlaylistNavButtons();
            });

            $('#breadCrumbs').html(data.breadCrumbs);

            if ('undefined' != typeof(data.title) && data.title != '' ) {
                document.title = data.title;
            }

        }
    });
    return false;
}


PlayerController.prototype.playListSearch = function(searchString){
    var t = this;
    if (!$('.ac_results').length){
        showAutoCompleteHint = false;
    }
    ClassLoader.ShowSmallLoader('#pListRightBar');
   
    searchString = searchString.replace('?', '&');
     
    var changedSearchString = encodeURIComponent(searchString);
    //var changedSearchString = searchString.replace('?', '&');
   
    $.ajax({
        type: 'GET',
        url: '/Playlist/_AjaxSearch?search_phrase=' + changedSearchString,
        dataType: 'json',
        //data: {searchString: changedSearchString},
        success: function(data){
            t.handleResults(data.html);

            $('#breadCrumbs').html(data.breadCrumbs);
            
            if ('undefined' != typeof(data.title) && data.title != '' ) {
                document.title = data.title;
            }

            document.location.href = '#/search/' + navigationUrlParamCutter(searchString);
        },
        complete: function(){
            
            Navigation.getNavigationInfo(0,function(){
                Navigation.initPlaylistNavButtons();
            });
            
            ClassLoader.HideSmallLoader();
            this.searchStarted = false;
        }
    });
  
}

PlayerController.prototype.addSongToPlayList = function(idSong){
    if (!idSong || "undefined" == typeof idSong){
        alert('Невозможно добавить песню в плейлист т.к. не передан идентификатор песни.', 'Ошибка!');
        return false;
    }

    dllAddToPlayList.show('Добавление песни в плейлист', '/playlist/_AjaxGetAddSongToPlaylistForm', {
        idSong: idSong
    });
    return false;
}

PlayerController.prototype.addAlbumToPlayList = function(idAlbum){

    if (!idAlbum || "undefined" == typeof idAlbum){
        alert('Невозможно добавить альбом в плейлист т.к. не передан идентификатор альбома.', 'Ошибка!');
        return false;
    }

    dllAddToPlayList.show('Добавление альбома в плейлист', '/playlist/_AjaxGetAddAlbumToPlaylistForm', {
        idAlbum: idAlbum
    });
    return false;
}

PlayerController.prototype.addArtistToPlayList = function(idArtist){

    if (!idArtist || "undefined" == typeof idArtist){
        alert('Невозможно добавить артиста в плейлист т.к. не передан идентификатор артиста.', 'Ошибка!');
        return false;
    }

    dllAddToPlayList.show('Добавление артиста в плейлист', '/Playlist/_AjaxGetAddArtistToPlaylistForm', {
        idArtist: idArtist
    });
    return false;
}

PlayerController.prototype.addToPlayList = function(idPlayList, playedType, idPlayed, callback, orderId){
    //alert($('div.panel[value=' + parseInt(idPlayList) + ']').html());
    ClassLoader.ShowBigLoader();
    if (dllAddToPlayList.isVisible()){
        dllAddToPlayList.close();
    }
    var t = this;
    $.ajax({
        url: '/playlist/_AjaxAddToPlayList',
        type : 'GET',
        success : function(data){
            if ('1' !== data){
                alert(data, 'Ошибка!');
            }else{
                //xmlrpc_playlist_list_reload(playlist_id,0,0);
                //refreshPlaylist();

                var panel = $('div.panel[value=' + idPlayList + ']');
                if (panel.length){
                    t.reloadPlayList(panel);
                }else{
                    refreshPlaylistList();
                }
                if ('undefined' != typeof callback && callback){
                    callback();
                }
            }
        },
        complete: function(){
            ClassLoader.HideBigLoader();
        },
        error:function(){
            alert('Не удалось добавить песню в плейлист', 'Ошибка');
        },
        data : {
            playedType: playedType,
            idPlayed: idPlayed,
            idPlayList: idPlayList,
            orderId: parseInt(orderId)
        }
    });
}

PlayerController.prototype.addToNewPlayList = function(playedType, idPlayed, title){
    ClassLoader.ShowBigLoader();
    if ('undefined' == typeof title){
        title = $("#playlistTitle").val();
    }
    if (dllAddToPlayList.isVisible()){
        dllAddToPlayList.close();
    }

    $.ajax({
        url: '/playlist/_AjaxAddToNewPlayList',
        type : 'GET',
        success : function(data){
            if (!parseInt(data)){
                alert(data, 'Ошибка!');
            }else{
                refreshPlaylistList();
                listCreator.loadNewList(parseInt(data));
            }
        },
        complete: function(){
            ClassLoader.HideBigLoader();
            calculatePlayListsCount();
        },
        error:function(){
            alert('Не удалось создать плейлист', 'Ошибка');
        },
        data : {
            playedType: playedType,
            idPlayed: idPlayed,
            title: title
        }
    });
}



var calculatePlayListsCount = function(){
    playListsCount = $('#userPlaylistsBlock .panel').length;
}

$(function(){
    if ('function' == typeof calculatePlayListsCount){
        calculatePlayListsCount();
    }
});

var calculateElementsCount = function(){

    var count = playListsCount + 7;
    if (count < 10 ){
        count = 10;
    }else if (count > 30 ){
        count = 30;
    }else{
        var ost = count % 5;
        count = parseInt(count / 5) * 5;
        if (ost >= 3){
            count += 5;
        }
    }

    return count;
}

