﻿var UserTemplatePlaylistHandlerApi = {

    AddTempPlaylistTracks: function(playlistId) {
        MusicPortal.Web.Services.Player.AddTempPlaylistTracks(playlistId,
            function() { }, function() { }, ctrl);
    }
};

UserTemplatePlaylistHandlerBuilder = function(ctrl, streamingSubscriptionAllowed, playlists) {
    var _p = UserTemplatePlaylistHandlerBuilder.prototype;
    this.ctrl = ctrl;
    this.playlists = playlists;
    this.streamingSubscriptionAllowed = streamingSubscriptionAllowed;
    ctrl.html("");

    var that = this;

    _p.createListItems = function(OKFunction, CancelFunction, productId) {
        var e = $("<div id='UserTemplatePlaylistHandlerDiv'/>");
        e.css("background-color", "#F0F9F9")
        //if (that.streamingSubscriptionAllowed == true) {
        e.append($('<span style="color:#000000">Сохранить в плейлист?</span>'));
        e.append($('<br/>'))
        var ul = $("<ul type='none' />");
        for (var i = 0; i < that.playlists.length; i++) {
            var playlist = that.playlists[i];
            var listiItem = $("<li class='UserTemplatePlaylistHandlerLI' />");
            listiItem.css("color", "#000000");
            var listItemRadio = $('<input type="radio" value="' + playlist.Id + '"  ' +
                ((i == 0 || that.streamingSubscriptionAllowed) ? '' : 'disabled="disabled"')
                + ' name="utpgroup" class="radioBtn" />');
            listiItem.append(listItemRadio);
            var listItemLabel = $('<span class="UserTemplatePlaylistHandlerLabel"/>')
            listItemLabel.css('color', ((i == 0 || that.streamingSubscriptionAllowed) ? '#000000' : '#A0A4A4'));
            listItemLabel.html(playlist.Title);
            listiItem.append(listItemLabel);
            ul.append(listiItem);
        }
        var listiItem = $('<li class="UserTemplatePlaylistHandlerLI" />');
        var listItemRadio = $('<input type="radio" ' + ((that.streamingSubscriptionAllowed || that.playlists.length == 0) ? '' : 'disabled="disabled"') + ' value="0" name="utpgroup" class="radioBtn"/>');
        listiItem.append(listItemRadio);
        var listItemTitle = $('<input type="text" id="newPlaylistName" ' + ((that.streamingSubscriptionAllowed || that.playlists.length == 0) ? '' : 'disabled="disabled"') + '/>');
        listiItem.append(listItemTitle);
        ul.append(listiItem);
        e.append(ul);
        //        }
        //        else {
        //            var span = $("<span id='UserTemplatePlaylistHandlerText'/>");
        //            span.css("color", "#000000");
        //            span.html("Сохранить треки из временного плейлиста в Вашем?");
        //            e.append(span);
        //        }

        var errorDiv = $("<div id='UserTemplatePlaylistHandlerErrorDiv' />");
        var errorText = $("<span class='UserTemplatePlaylistHandlerText' style='color:Red'/>")
        errorDiv.append(errorText);
        e.append(errorDiv)

        var buttonDiv = $("<div id='UserTemplatePlaylistHandlerButtonDiv' />");
        var listItemTitle = $("<input type='text' id='newPlaylistTitle' title='Введите название нового плейлиста'/>");
        var OkButton = $("<input type='button' />");
        OkButton.click(function(event) {
            var errorSpan = $("span.UserTemplatePlaylistHandlerText");
            var radio = $("input:radio:checked[name='utpgroup']");
            if (radio.length > 0) {
                var id = radio.val();
                var title = new String();

                if (id != 0)
                    title = $("input:radio:checked[name='utpgroup'] + span")[0].textContent.trim();
                else
                    title = $("input:radio:checked[name='utpgroup'] + input").val().trim();
                if (title.trim() == "") {
                    errorSpan.html("Не заполнено поле с названием нового плейлиста");
                    return;
                }
                if (title.length > 30) {
                    errorSpan.html("Название плейлиста не должно быть больше 30 сомволов");
                    return;
                }
                else
                    errorSpan.html("");
                if (productId) {
                    ExecuteService("/Services/Player.asmx/AddProductToUserPlaylist", "{productId:'" + productId + "', playlistId: " + id + ", playlistTitle:'" + title + "'}", true,
                    OKFunction,
                    function() {
                        errorSpan.html("Ошибка при сохранении. Попробуйте еще раз.");
                        return;
                    });
                }
                else {
                    ExecuteService("/Services/Player.asmx/AddTempTracksToPlaylist", "{id: " + id + ", title:'" + title + "'}", true,
                    OKFunction,
                    function() {
                        errorSpan.html("Ошибка при сохранении. Попробуйте еще раз.");
                        return;
                    });
                }
            }
            else {
                //                if (that.streamingSubscriptionAllowed != true) {
                //                    ExecuteService("/Services/Player.asmx/AddTempTracksToPlaylist", "{id: -1, title:''}", true,
                //                    OKFunction,
                //                    function() {
                //                        errorSpan.html("Ошибка при сохранении. Попробуйте еще раз.");
                //                        return;
                //                    });
                //                }
                //                else {
                errorSpan.html("Выберите плейлист из списка");
                return;
                //                }
            }
        });
        OkButton.attr("title", "Сохранить");
        OkButton.val("Сохранить");
        var CancelButton = $("<input type='button' />");
        CancelButton.click(CancelFunction);
        CancelButton.attr("title", "Отмена");
        CancelButton.val("Отмена");
        buttonDiv.append(OkButton);
        buttonDiv.append(CancelButton);
        e.append(buttonDiv);
        this.ctrl.append(e);
        return e;
    };

    _p.errorAlert = function(ctrl, message) {

    }
};


(function($) {
    $.fn.userTempPlaylistHandler = function(streamingSubscriptionAllowed, playlists, OKFunction, CancelFunction, productId) {
        var builder = new UserTemplatePlaylistHandlerBuilder($(this), streamingSubscriptionAllowed, playlists);
        var userTemplatePlaylist = builder.createListItems(OKFunction, CancelFunction, productId);
    };
})(jQuery);

function ExecuteService(url, params, async, callbackSuccess, callbackError) {
    $.ajax({
        async: async,
        cache: false,
        type: "POST",
        url: url,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        data: params,
        success: callbackSuccess,
        error: callbackError
    });
}
