﻿var BuyButtonApi = {

    DoSms: function(productId, ctrl) {
        window.open("/Store/SmsBuyPopup.aspx?ProductId=" + productId + "&VariantId=0", "smsBuyWindow", "resizable=0, width=630px, height=630px, left=100px, top=50px");
    },

    DoBuy: function(productId, ctrl) {
        MusicPortal.Web.Services.OrderService.AddProductToNewBasket(productId,
        function(result, e) {
            if (result != '-1') {
                var car;
                if (opener != null)
                    car = $(opener.document.getElementById("CarTotal"));
                else car = $("#CarTotal");

                if (car != null) {
                    car.html(result);
                }

                BuyButtonApi.ConvertToBasketLink($(e), "В корзине");
            }
            else {
                alert("Выбранный Вами товар уже есть в корзине");
            }
        },
        function(result, e) {
            if (result._message == "notAuthorized") {
                alert('Данная функция доступна только зарегистрированным пользователям');
            }
            else {
                alert('В данный момент произвести покупку не удается (' + result._message + ').');
            }
        }, ctrl);
    },

    DoImmediateBuy: function(productId, ctrl) {
        if (productId.startsWith('A'))
            MusicPortal.Web.Services.OrderService.BuyAlbumOneClick(productId, BuyButtonApi.ImmediateBuySuccess, function() { }, ctrl);
        else
            MusicPortal.Web.Services.OrderService.BuyTrackOneClick(productId, BuyButtonApi.ImmediateBuySuccess, function() { }, ctrl);
    },

    ImmediateBuySuccess: function(result, e) {
        if (result == 'error:1') { alert('Средств на электронном счете недостаточно для покупки'); }
        else if (result == '') { alert('Произошел сбой. Повторите попытку позднее.'); }
        else {
            BuyButtonApi.DisableBuyButton($(e), "Скачано");
            var detailsLinkSource = $("#CheckoutLink").val();
            var detailsLink = detailsLinkSource.replace("{0}", result);
            window.open(detailsLink);
        }
    },

    DisableBuyButton: function(ctrl, text) {
        if (ctrl != null) {
            ctrl.attr("disabled", "true");
            ctrl.val(text);
            ctrl.css("font-size", "12px");
            ctrl.unbind("click");
        }
    },

    ConvertToBasketLink: function(ctrl, text) {
        if (ctrl != null) {
            ctrl.val(text);
            ctrl.css("font-size", "12px");
            ctrl.attr("title", "Товар в корзине - нажмите, чтобы перейти в корзину");
            ctrl.unbind("click");
            ctrl.click(function() {
                if (opener != null)
                    opener.location.href = "/Checkout/Cart2.aspx";
                else
                    location.href = "/Checkout/Cart2.aspx";
            });
        }
    },

    DoLogonRequired: function(productId) {
        alert('Вы не авторизованы. Авторизуйтесь, пожалуйста.')
    },

    DoBuySubscription: function(productId) {
        alert("Купите подписку на неограниченное скачивание");
    },

    GetLeafLicense: function(trackId) {
        try {
            var obj = document.getElementById("netobj");
            var drmversion = obj.GetDRMSecurityVersion();
        }
        catch (e) {
            return;
        }
        var drmversionarray = drmversion.split(".");
        if ((drmversionarray[drmversionarray.length - 1] == "1") || (drmversionarray[drmversionarray.length - 1] == "3") || (drmversionarray[drmversionarray.length - 1] == "5") || (drmversionarray[drmversionarray.length - 1] == "7") || (drmversionarray[drmversionarray.length - 1] == "9")) {
            var cinfo = obj.GetSystemInfo();
            MusicPortal.Web.Services.LicenseService.GetLeafLicense(cinfo, trackId, BuyButtonApi.OnGetLeafLicenseSuccess, BuyButtonApi.OnGetLeafLicenseFailure);
        }
        else {
            return;
        }
    },

    OnGetLeafLicenseSuccess: function(result, eventArgs) {
        var obj = document.getElementById("netobj");
        obj.StoreLicense(result);
    },

    OnGetLeafLicenseFailure: function(error) {
    },
    AppendToPlaylist: function(productId, userAuthenticated, streamingSubscriptionAllowed, linkRef) {

        if (userAuthenticated) {
            ShowSavePlDlg("#SaveToPl", "Выбирите плейлист для сохранения", productId, linkRef);
        }
        else {
            PlayTrackInCurPl(productId, false, -1);
        }
        $(".popup_menu").hide(300);
    },

    OpenPlaylistsWindow: function() {
        window.open("/Store/FreeStreaming2.aspx", "freestreaming", "width=1000,height=670");
    }
};

String.prototype.startsWith = function(str) {
    return (this.indexOf(str) === 0);
}

ButtonBuilder = function(ctrl, options) {
    var _p = ButtonBuilder.prototype;
    this.ctrl = ctrl;
    this.options = options;
    ctrl.html("");
    ctrl.css("position", "relative");
    _p.s4 = function() {
        return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
    }
    this.uniqueId = "u" + this.s4();

    var that = this;

    _p.createButton = function() {
        var e = $("<input type='button' />");
        e.attr("id", "b" + this.uniqueId);
        e.attr("title", "Нажмите, чтобы купить этот " + this.getProductUserFriendlyName());
        e.val("Купить");
        e.addClass("buyBtn");
        if (!this.options.available)
            e.attr("disabled", "disabled");
        else
            e.click(function() {
                eval("BuyButtonApi." + that.FunctionToCall())(that.options.productCsId, this);
            });
        this.ctrl.append(e);
        return e;
    };
    _p.createDropdown = function() {
        var e = $("<input type='button' />");
        e.attr("id", "v" + this.uniqueId);
        e.val("▼");
        e.attr("title", "Нажмите, чтобы воспользоваться дополнительными возможностями");
        e.addClass("moreOptions");
        if (!this.options.available)
            e.attr("disabled", "disabled");
        else
            e.click(function(event) {
                $(".popup_menu").hide(300);
                $("#m" + that.uniqueId).css("left", $(this).position().left + 20).css("top", $(this).position().top);
                $("#m" + that.uniqueId).show(300);
                event.stopPropagation();
            });
        this.ctrl.append(e);
    };
    _p.createMenu = function(mainBtn) {
        var m = $("<div />");
        m.attr("id", "m" + this.uniqueId);
        m.addClass("popup_menu");
        var ul = $("<ul />");
        var iBuy = $("<li />");
        var iBuyLink = $("<a />");
        iBuyLink.attr("href", "#");
        iBuyLink.click(function() {
            eval("BuyButtonApi." + that.FunctionToCall())(that.options.productCsId, mainBtn);
        });
        iBuyLink.html(this.getBuyDropDownItemText());
        iBuy.append(iBuyLink);
        ul.append(iBuy);
        if (this.options.userAuthenticated) {
            var iPresent = $("<li />");
            var iPresentLink = $("<a />");
            if (opener != null) {
                iPresentLink.attr("href", "#");
                iPresentLink.click(function() {
                    opener.location.href = "/Store/MakePresent.aspx?ProductId=" + that.options.productCsId;
                    $("#m" + that.uniqueId).hide(300);
                    return false;
                });
            }
            else
                iPresentLink.attr("href", "/Store/MakePresent.aspx?ProductId=" + this.options.productCsId);
            iPresentLink.html("Подарить " + this.getProductUserFriendlyName());
            iPresent.append(iPresentLink);
            ul.append(iPresent);
            if (this.options.productType != "album") {
                var iDownload = $("<li />");
                var iDownloadLink;
                if (this.options.downloadSubscriptionAllowed) {
                    iDownloadLink = $("<a />");
                    iDownloadLink.attr("id", "d" + this.uniqueId);
                    iDownloadLink.attr("href", "#");
                    iDownloadLink.click(function() {
                        BuyButtonApi.GetLeafLicense(that.options.productId);
                        window.open("/Account/PrepareDownload.ashx?id=" + that.options.productId + "&variantId=1&name=name");
                    });
                }
                else {
                    iDownloadLink = $("<span />");
                    iDownloadLink.css("color", "#cccccc");
                }
                iDownloadLink.html("Скачать по подписке");
                iDownload.append(iDownloadLink);
                ul.append(iDownload);

                if (this.options.productType != "movieClip" && this.options.productType != "audioTrack") //remove && this.options.productType != "audioTrack" to enable mp3 subscription
                {
                    var iDownloadMp3 = $("<li />");
                    var iDownloadMp3Link;
                    if (this.options.downloadMp3Allowed) {
                        iDownloadMp3Link = $("<a />");
                        iDownloadMp3Link.attr("href", "#");
                        iDownloadMp3Link.click(function(event) {
                            event.preventDefault();
                            window.open("/Account/PrepareDownloadMp3.aspx?id=" + that.options.productId);
                        });
                    }
                    else {
                        iDownloadMp3Link = $("<span />");
                        iDownloadMp3Link.css("color", "#cccccc");
                    }
                    iDownloadMp3Link.html("Скачать mp3");
                    iDownloadMp3.append(iDownloadMp3Link);
                    ul.append(iDownloadMp3);
                }
            }
        }
        else {
            if (this.options.productType == "audioTrack") {
                var iAddToBasket = $("<li />");
                var iAddToBasketLink = $("<a />");
                iAddToBasketLink.attr("href", "#");
                iAddToBasketLink.click(function() {
                    eval("BuyButtonApi.DoBuy")(that.options.productCsId, mainBtn);
                });
                iAddToBasketLink.html("Добавить в корзину");
                iAddToBasket.append(iAddToBasketLink);
                ul.append(iAddToBasket);
            }
        }
        var iAdd2Playlist = $("<li />");
        var iAdd2PlaylistLink;
        if (this.options.displayAdd2Playlist && this.options.productType != "movieClip") {
            iAdd2PlaylistLink = $("<a />");
            iAdd2PlaylistLink.attr("id", "p" + this.uniqueId);
            iAdd2PlaylistLink.attr("href", "#");
            iAdd2PlaylistLink.click(function() {
                var link = $(this);
                BuyButtonApi.AppendToPlaylist(that.options.productCsId,
                    that.options.userAuthenticated,
                    that.options.streamingSubscriptionAllowed, link);
                //				link.html("Добавлено");
                //				link.attr("title", "Нажмите, чтобы открыть окно с плейлистами");
                //				link.unbind("click");
                //				link.css("color", "#cccccc").css("text-decoration", "none");
                //				link.click(function() { BuyButtonApi.OpenPlaylistsWindow(); });
                return false;
            });
        }
        else {
            iAdd2PlaylistLink = $("<span />");
            iAdd2PlaylistLink.css("color", "#cccccc");
        }
        iAdd2PlaylistLink.html("Добавить в плейлист");
        iAdd2Playlist.append(iAdd2PlaylistLink);
        ul.append(iAdd2Playlist);
        m.append(ul);
        m.append($("<div class='clear' />"));
        this.ctrl.append(m);
    };
    _p.getProductUserFriendlyName = function() {
        if (this.options.productType == "album") return "альбом";
        if (this.options.productType == "audioTrack") return "аудио-трек";
        if (this.options.productType == "movieClip") return "клип";
    };

    _p.getBuyDropDownItemText = function() {
        if (this.options.productType == "album") {
            if (this.options.userAuthenticated)
                return "Купить " + this.getProductUserFriendlyName();
            else
                return "Добавить в корзину";
        }
        if (this.options.productType == "audioTrack") {
            if (this.options.userAuthenticated)
                return "Купить " + this.getProductUserFriendlyName();
            else
                return "Оплатить по SMS";
        }
        if (this.options.productType == "movieClip")
            return "Купить " + this.getProductUserFriendlyName();
    };
    _p.FunctionToCall = function() {
        if (!this.options.userAuthenticated) {
            if (this.options.productType == "album") {
                return "DoBuy";
            }
            return "DoSms";
        }
        return this.options.immediateBuy ? "DoImmediateBuy" : "DoBuy";
    };
};


(function($) {
    $.fn.buyButton = function(options) {
        var defaults = {
            productCsId: '',
            productId: 0,
            productType: 'audioTrack',
            available: true,
            downloadSubscriptionAllowed: false,
            streamingSubscriptionAllowed: false,
			downloadMp3Allowed: false,            
            userAuthenticated: false,
            immediateBuy: false,
            displayAdd2Playlist: true,
            showDropdown: true
        }, opts = $.extend(defaults, options);
        $(document).click(function() {
            $(".popup_menu").hide(300);
        });
        this.each(function(i, o) {
            var builder = new ButtonBuilder($(o), opts)
            var mainBtn = builder.createButton();
            if (opts.showDropdown) {
                builder.createDropdown();
                if (opts.available) // if (opts.userAuthenticated && opts.available)
                    builder.createMenu(mainBtn);
            }
        });
    };
})(jQuery);

$(function()
{
	$("div.buy_button_container").each(function(i, e)
	{
		var container = $(e);
		var opts = {};
		opts_available = container.find("input.buy_button_opt_available");
		if (opts_available.length > 0)
			opts.available = opts_available.val() == "true";
		opts_productCsId = container.find("input.buy_button_opt_productCsId");
		if (opts_productCsId.length > 0)
			opts.productCsId = opts_productCsId.val();
		opts_productType = container.find("input.buy_button_opt_productType");
		if (opts_productType.length > 0)
			opts.productType = opts_productType.val();
		opts_productId = container.find("input.buy_button_opt_productId");
		if (opts_productId.length > 0)
			opts.productId = parseInt(opts_productId.val());
		opts_userAuthenticated = container.find("input.buy_button_opt_userAuthenticated");
		if (opts_userAuthenticated.length > 0)
			opts.userAuthenticated = opts_userAuthenticated.val() == "true";
		opts_downloadSubscriptionAllowed = container.find("input.buy_button_opt_downloadSubscriptionAllowed");
		if (opts_downloadSubscriptionAllowed.length > 0)
			opts.downloadSubscriptionAllowed = opts_downloadSubscriptionAllowed.val() == "true";
		opts_streamingSubscriptionAllowed = container.find("input.buy_button_opt_streamingSubscriptionAllowed");
		if (opts_streamingSubscriptionAllowed.length > 0)
			opts.streamingSubscriptionAllowed = opts_streamingSubscriptionAllowed.val() == "true";
		opts_downloadMp3Allowed = container.find("input.buy_button_opt_mp3download");
		if (opts_downloadMp3Allowed.length > 0)
			opts.downloadMp3Allowed = opts_downloadMp3Allowed.val() == "true";
		opts_immediateBuy = container.find("input.buy_button_opt_immediateBuy");
		if (opts_immediateBuy.length > 0)
			opts.immediateBuy = opts_immediateBuy.val() == "true";
		container.buyButton(opts);
	});
});


function GetExInfo(albumCSId, e) {
    $.ajax({
        type: "POST",
        url: "/Services/PopupServices.asmx/GetAlbumInfo",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        data: "{ albumCsId: '" + albumCSId + "'}",
        success: function(data) {
            $(e).after($.tmpl($("#popupTemplate"), JSON.parse(data.d)));
        }
    });
}

