﻿
// popup window Download Subscription
CreateSubscriptionPopUp = function() {
window.open('SubscriptionPopUp.aspx', '', 'width=500,height=470, toolbar=0', false);
    return false;
}

// popup window Channels Subscription
CreateChannelSubscriptionPopUp = function() {
    window.open('ChannelSubscriptionPopUp.aspx', '', 'width=500,height=580, toolbar=0', false);
    return false;
}

// agreement Panel
IsAgreed = function() {
    var pnlAgree = document.getElementById("chkAgree");
    if (pnlAgree != null) {
        if (pnlAgree.checked == true)
            return true;
        else
            alert('Вы должны согласиться с условиями');
        return false;
    }
    return false;
}

function refreshParent() {

    if (window.opener) {
        window.opener.location.reload();
        /*
        window.opener.location.href = window.opener.location.href;

    if (window.opener.progressWindow) {
        window.opener.progressWindow.close()
        }*/
        window.close();
    }
    else
        window.location.reload();    
}

// message
var message = "Все подписки созданы";

// associative list
var channelList = []; //new Array();
var channelListByDays = [];

function HashTable() {
    this.hashArr = new Array(100);
    this.length = 0;
}

HashTable.prototype.get = function(key) {
    return this.hashArr[key];
};

HashTable.prototype.put = function(key, value) {    
    if (typeof (this.hashArr[key]) == 'undefined') {
        this.length++;
    }
    this.hashArr[key] = value;
};

HashTable.prototype.remove = function(key) {
    if (typeof (this.hashArr[key]) != 'undefined') {
        this.length--;
        var value = this.hashArr[key];
        delete this.hashArr[key];
        return value;
    }
};


HashTable.prototype.has = function(key) {
    return (typeof (this.hashArr[key]) != 'undefined');
};

var channelHashTable = new HashTable();
var BasicPrice = 0;
var collTotalPrice = 0;

    function OnChanged(id, IdByPrices, iItem, PricePerDay, ParentID, BasicSubPrice) {

        Clear();

        var cntBasicSubPrice = document.getElementById(BasicSubPrice);

        // serious error - cannot define a Basic Price!
        if (cntBasicSubPrice == null) {
            //RetrieveInfoDiv('Internal Service error');
            //return;
            
        }
        else
            BasicPrice = cntBasicSubPrice.value;        
        
        var SliderCnt = document.getElementById(id);
        var CntByPrices = document.getElementById(IdByPrices);        
        
        if (SliderCnt != null && CntByPrices != null) {

            var Price = PricePerDay * SliderCnt.innerHTML;            
            var SelectedDays = SliderCnt.innerHTML;
            CntByPrices.innerHTML = Price;
            collTotalPrice = Price;
            OnChangedTotalPrice(iItem, Price, SelectedDays, ParentID);                  
        }
    }
    
    function CreatePremiumSubscription() {
        
        for (i in channelListByDays) {

            if (i == 'undefined' || i == 'append')
                continue;

            var arrProductID = i;
            var arrTotalDays = channelListByDays[i];
            // remove used element
            delete channelListByDays[i];
            CreateSubScription(arrProductID, arrTotalDays);
            return;
            //break;
        }
        //reload current page
        //window.location.reload();
    }

    //--------------- PROLONG BASIC SUBSCRIPTION --------------------------------
    function CreateBasicChannelSubscription(ProductId, Controlprolongdays, ListPrice) {
        var Days = document.getElementById(Controlprolongdays).innerHTML;
        if (Days == '0') {
            alert('Вы не установили количество дней');
            return;
        }
        ProlongSubscription(ProductId, Days, ListPrice, false);
    }
    
    //////////////// PROLONG SUBSCRIPTION ////////////////////////
    function ProlongSubscription(ProductId, TotalDays, ListPrice, isDownload) {
        
        var balance = parseFloat(document.getElementById("UserBalance").value);        
        if (ListPrice * TotalDays > balance) {
            alert("Недостаточно средств на счете");
            return;
        }
        
        if (DetectBrowser()) {
            if (IsMediaCenterUpdated()) {

                if (confirm("С вашего счета будет списано " + ListPrice * TotalDays + " руб. Продолжить?")) {
                    RetrieveInfoDiv("Продление подписки " + ProductId + " ....");
                    ModalWaitingDialog('open');
                    MusicPortal.Web.Services.SubscriptionService.ProlongSubscription(ProductId, TotalDays, isDownload, OnProlongSuccess, OnProlongFailure);
                }
            }
        }
        else
            alert('Для продления подписки Вам необходим броузер Internet Explorer версии 6 и выше');

    }
    
    function OnProlongSuccess(result, eventArgs) {
        if (result == null || result == "") {
            ModalWaitingDialog('close');
            RetrieveInfoDiv('Internal web service error');
            return;
        }
                
        //alert('Подписка продлена');
        message = 'Подписка продлена';
        GetRootLicense(result);
        //reload current page
        //window.location.reload();
    }
    
    function OnProlongFailure(error) {
        ModalWaitingDialog('close');
        RetrieveInfoDiv(error.get_message());
        alert(error.get_message());
    }    
    //-------------- end prolong subscription
    
    
    function CreateChannelSubscription(BasicChannelID, Sender) {
        // take total money from basic channel
        var cnt = document.getElementById(Sender);
        // create basic channel subscription
        CreateSubScription(BasicChannelID,cnt.innerHTML); 
    }
    
    function SetBasicChannelValue(Sender, Price, IdByPrices) {        
        var CntByPrices = document.getElementById(IdByPrices);
        channelList[Sender] = Price;        
        //OnChangedTotalPrice(Sender, Price, ParentID);
    }
    
    
    
    var isNumeric = function(x) {
        // returns true if x is numeric and false if it is not.
        var RegExp = /^(-)?(\d*)(\.?)(\d*)$/;
        return String(x).match(RegExp);
    }
    
    
    function OnChangedTotalPrice(Sender, Price, Days, ParentID) {

        // to add or update Value in associate list        
        channelList[Sender] = Price;
        channelListByDays[Sender] = Days;       
            
        // to show ALL prices
        var TotalPrice = Math.floor(BasicPrice);
        var TotalPremiumPrice = 0;
        var TotalPremiumCount = 0;
        for (i in channelList) {
            if (isNumeric(channelList[i])) {
                if (channelList[i] == 0) continue;
                    TotalPrice += channelList[i];
                    TotalPremiumPrice += channelList[i];
                    TotalPremiumCount++;               
            }
       }
       
       // info div for Premium List
       if (document.getElementById("totalPremiumCount")!= null) {
           document.getElementById("totalPremiumCount").innerHTML = TotalPremiumCount;
       }
       if(document.getElementById("totalPremiumPrice") != null)  
       {
           document.getElementById("totalPremiumPrice").innerHTML = TotalPremiumPrice;
       }

       collTotalPrice = TotalPrice;       
       
        // just for information
       var cntInfo = document.getElementById(ParentID);
       if (cntInfo != null) {
           cntInfo.innerHTML = TotalPrice;
       }
            
    }

 
// create subscriptions by WebService
function CreateSubScription(ProductId,TotalDays, FunctionAfter) {
    
    var balance = parseFloat(document.getElementById("UserBalance").value);
    if (collTotalPrice > balance) {
        alert("Недостаточно средств на счете");
        return;
    }
    
    if (DetectBrowser()) {
        globalFunctionAfter = FunctionAfter;
        if (IsMediaCenterUpdated()) {
            RetrieveInfoDiv("Создание подписки " + ProductId + " ....");
            ModalWaitingDialog('open');
            MusicPortal.Web.Services.SubscriptionService.CreateChannelsSubscription(ProductId, TotalDays, OnChannelSuccess, OnChannelFailure);
        }
    }
    else
        alert('Для оформления подписки Вам необходим броузер Internet Explorer версии 6 и выше');
        
}

function OnChannelSuccess(result, eventArgs) {
    if (result == null || result == "") {
        ModalWaitingDialog('close');
        RetrieveInfoDiv('Internal web service error');
        return;
    }    
    GetRootLicense(result);
}

////////////// VISIBLE FUNCTIONS //////////////
function RetrieveInfoDiv(Text) {
    
    var InfoDiv = document.getElementById("ServiceResponse");
    if (InfoDiv != null)
        InfoDiv.innerHTML = Text;
}

function Clear() {
    RetrieveInfoDiv("");
}

function ModalWaitingDialog(mode) {
    $("#dialog").dialog(mode);
    //$("#dialog").dialog('option', 'trackid', trackId);
    //$("#dialog").dialog('option', 'width', 340);
}
///////////////////////////////////////////////////


function OnChannelFailure(error) {
    RetrieveInfoDiv(error.get_message());
    ModalWaitingDialog('close');
    alert('Internal error: ' + error.get_message());
}
function OnGetRootLicenseSuccess(result, eventArgs) {
    ModalWaitingDialog('close');
    if (result == null || result == '') {
        RetrieveInfoDiv('internal License error');
        return;
    }
    var obj = document.getElementById("netobj");
    obj.StoreLicense(result);

    for (i in channelListByDays) {

        if (i == 'undefined' || i == 'append')
            continue;

        var arrProductID = i;
        var arrTotalDays = channelListByDays[i];
        // remove used element
        delete channelListByDays[i];       
        CreateSubScription(arrProductID, arrTotalDays);
        //GetRootLicense(arrProductID);
        return;
    }

    RetrieveInfoDiv("Все подписки созданы");
    alert(message);

    //reload current page
    //if(globalFunctionAfter != null && globalFunctionAfter != 'undefined')
    //    eval(globalFunctionAfter);
    refreshParent();

}

//////////////////// failed running GetRootLicense
function OnGetRootLicenseFailure(error) {
    ModalWaitingDialog('close');
    RetrieveInfoDiv(error.get_message());
    alert('Internal error: ' + error.get_message());
    //reload current page
    refreshParent();
}

//////////////// checking Media Center has a necessary udpate /////////
function IsMediaCenterUpdated() {
    try {
        var obj = document.getElementById("netobj");
        var drmversion = obj.GetDRMSecurityVersion();
    }
    catch (e) {        
        return false;
    }
    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")) {
        return true;
    }
    else {
        alert("Не установлены обновления для Windows Media Player");
        return false;
    }
}


function GetRootLicense(productId) {
    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();
            var licenseResponse = MusicPortal.Web.Services.LicenseService.GetRootLicense(productId, cinfo, OnGetRootLicenseSuccess, OnGetRootLicenseFailure);     
       
    }
    else {
        alert("Не установлены обновления для Windows Media Player");
    }
}
function GetLeafLicense(productId, variantId) {
    try {
        debugger;
        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();
        var licenseResponse = MusicPortal.Web.Services.LicenseService.GetLeafLicense(productId, variantId, cinfo, OnGetLeafLicenseSuccess, OnGetLeafLicenseFailure);

    }
    else {
        return;
    }
}
function OnGetLeafLicenseSuccess(result, eventArgs) {
    var obj = document.getElementById("netobj");
    obj.StoreLicense(result);
}
function DetectBrowser() {
    var browser = navigator.appName;
    var b_version = navigator.appVersion;
    var version = parseFloat(b_version);
    if (!((browser == "Microsoft Internet Explorer") && (version < 6))) {
        //alert("Для загрузки этого файла необходимо использовать Microsoft Internet Explorer версии 6.0 и выше");
        return false;
    }
    return true;
} function OnGetLeafLicenseFailure(error) {
debugger;
}

