var PlaylistPen = 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;
    }

    if ('undefined' != typeof(data.title)){
        this.title = data.title;
    }else{
        this.title = '';
    }
    if ('undefined' != typeof(data.isCreation)){
        this.isCreation = data.isCreation;
    }else{
        this.isCreation = false;
    }

    this.init();
}


PlaylistPen.prototype.dialog;
PlaylistPen.prototype.linkClass;
PlaylistPen.prototype.oldContent;
PlaylistPen.prototype.idSended;
PlaylistPen.prototype.ajaxFormURL;
PlaylistPen.prototype.title = '';
PlaylistPen.prototype.isCreation = false;


PlaylistPen.prototype.init = function(){
    var t = this;

    $('.' + this.linkClass).unbind('click');
    $('.' + this.linkClass).each(function(){
        $(this).bind('click', function(){
            if ('undefined' != typeof ( $(this).parent().attr('value')) ) {
                t.idSended = $(this).parent().attr('value');
            } else {
                t.idSended = 0;
            }
            t.initDialog($(this).parent());
            t.dialog.dialog('open');
            return false;
        });
    });
  
}


PlaylistPen.prototype.destroyDlg = function(){
    $(this.dialog).dialog('close');
    $(this.dialog).dialog('destroy');
}


PlaylistPen.prototype.loadNewList = function(idList){

    if (!$('#userPlaylistsBlock').length){
        return;
    }

    $.post('/playlist/_AjaxPlaylistHTML', {
        id: idList
    }, function(data){
        if (!data){
            alert('При создании плейлиста произошла ошибка', 'Ошибка');
        }else{

            data = $('#userPlaylistsBlock').prepend(data).children().eq(0);

            var pList  = $('.panel', data);
            var idPlayList = pList.attr('value');
            player.handleAllActions(pList.next(), idList);
            player.handleDeletePlayList(pList);
            player.handlePlayPlayList(pList);
            player.handleDrop(pList);

            initPen();
            initSliderList($('.click', pList), '/playlist/_AjaxPlaylistSongs', player.handleAllActions, player);
            calculatePlayListsCount();

            refreshPlaylistList();//msq
        }
    });

}


PlaylistPen.prototype.initDialog = function(header){
    this.dialog = $('<div title="' + this.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(header);
                    }
                    return;
                }
                t.destroyDlg();
            }, 'json');
        }
    });
}


PlaylistPen.prototype.initAjaxForm = function(header){
    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':
                        $('.contentContainer', t.dialog).html(data.content);
                        return;
                    break;
                    case '1':
                        $('.contentContainer', t.dialog).html(data.content);
                        //init ajax form
                        t.initAjaxForm(header);
                        return;
                    break;
                    case '2':
                        if ('undefined' != typeof(data.additionalData) && data.additionalData.idPlaylist) {
                            var pTitle = $('input#title', t.dialog).val();
                            if (t.isCreation){//creation
                                t.loadNewList(data.additionalData.idPlaylist);
                            } else{//editing
                                $('h2 .lTitle', header).text(pTitle);
                                if ('undefined' != typeof(data.additionalData.updatePicture)) {
                                    var src = $('img.thumb', header).attr('src');
                                    src = '/files/playlists/' + header.attr('value') + '.jpg';
                                    var date = new Date();
                                    $('img.thumb', header).attr('src', src + '?t=' + date.getTime());
                                }
                            }

                            if ('undefined' != typeof(data.additionalData.showError)) {
                                $('.contentContainer', t.dialog).html(data.content);
                                return;
                            }
                        }
                    break;
                }
            }
            t.destroyDlg();
        },
        dataType: 'json'
    });
}


var pen;
var listCreator;


function initPen(){
    pen = new PlaylistPen({
        linkClass: 'btnEditPlayList',
        ajaxFormURL: '/playlist/_AjaxGetPlaylistForm',
        title: 'Редактирование плейлиста'
    });

    listCreator = new PlaylistPen({
        linkClass: 'hrefNewPlayList',
        ajaxFormURL: '/playlist/_AjaxGetPlaylistForm',
        title: 'Создание плейлиста',
        isCreation: true
    });
}