<script data-cfasync="false" type="text/javascript">
    var packagemanager = {};
    packagemanager.showperformonserver      = true; //default unless panel doesn't need to show this option
    packagemanager.paneldescription         = "";
    packagemanager.hasplugin                = <?php echo ($this->productinfo['hasplugin']=="") ? "false": "true";?>;
    //any panel setting type that requires lazy loading needs to be in this list
    packagemanager.arrayOfLazyLoadingPanels = ["hosting","domaininfo","hostrecords","nameservers", 'certinfo'];
    packagemanager.activeTab                = "<?php echo $this->activetab;?>";
    packagemanager.permissions              = null;
    packagemanager.producttype              = <?php echo $this->productinfo['producttype'];?>;
    packagemanager.package_id               = <?php echo $this->packageid;?>;
    packagemanager.newhostrecordid          = 0;
    <?php
    $js_array = json_encode($this->productinfo['panels']);
    echo "packagemanager.panels = ". $js_array . ";\n";
    ?>

    $(document).ready(function () {

        const $mobileMenu = $('.sidebar-mobile');
        const $desktopMenu = $('.tab-Sidebar');

        function syncTabUI(type) {
            const $allTabs = $mobileMenu.find('li.tab-link, li.tab-link') // mobile
                .add($desktopMenu.find('li.tab-link, li.tab-link'));      // desktop

            $allTabs.removeClass('current active');

            const sel = 'li.tab-link[data-settingtype="' + type + '"]';
            $mobileMenu.find(sel).addClass('current active');
            $desktopMenu.find(sel).addClass('current active');

            // close mobile dropdown if open
            $mobileMenu.removeClass('open');
        }

        $('.mobile-tab-toggle').on('click', function (e) {
            e.stopPropagation();
            $mobileMenu.toggleClass('open');
        });

        $(document).on('click', function (e) {
            if (!$mobileMenu.is(e.target) && $mobileMenu.has(e.target).length === 0) {
                $mobileMenu.removeClass('open');
            }
        });

        if (packagemanager && typeof packagemanager.showManageSettingByType === 'function') {
            const _orig = packagemanager.showManageSettingByType;

            packagemanager.showManageSettingByType = function (type) {
                packagemanager.activeTab = type;
                const ret = _orig.apply(packagemanager, arguments);
                syncTabUI(type);
                return ret;
            };
        }

        if (packagemanager && packagemanager.activeTab) {
            syncTabUI(packagemanager.activeTab);
        }
    });

</script>

<div class="client-pack-wrapper">

<div class="fixed-head package-header">
    <div class="package-main">
        <h2
            class="package-name"
            title="<?php echo $this->escape($this->productinfo['name']); ?>">
            <?php echo $this->escape($this->productinfo['name']); ?>
        </h2>

        <div class="package-details">
            <div class="detail">
                <span class="label"><?php echo $this->user->lang('Group'); ?></span>
                <span class="value">
                    <?php echo $this->productinfo['productgroupname']; ?>
                    <span class="muted">
                        (<?php echo $this->productinfo['producttypename']; ?>)
                    </span>
                </span>
            </div>

            <div class="detail">
                <span class="label"><?php echo $this->user->lang('Activated'); ?></span>
                <span class="value">
                    <?php echo $this->productinfo['dateactivated']; ?>
                </span>
            </div>

            <?php if ($this->productinfo['product_type'] == PACKAGE_TYPE_HOSTING && $this->productinfo['server_id'] != 0) { ?>
                <div class="detail">
                    <span class="label"><?php echo $this->user->lang('Server'); ?></span>
                    <span class="value">
                        <?php echo $this->productinfo['additional_details']; ?>
                        <?php if ($this->productinfo['pluginname'] != '') { ?>
                            <span class="muted">
                                (<?php echo $this->productinfo['pluginname']; ?>)
                            </span>
                        <?php } ?>
                    </span>
                </div>
            <?php } ?>
        </div>
    </div>

    <div class="package-actions">
        <div class="dropdown" id="divpluginactiondropdown">
            <button
                class="cm-btns orange dropdown-toggle btn-icon-only"
                type="button"
                id="pluginMenuButton"
                data-bs-toggle="dropdown"
                aria-expanded="false"
                title="Plugin Actions">
                <i class="fa fa-cog"></i>
            </button>
            <ul
                class="dropdown-menu"
                id="plugindropdown"
                aria-labelledby="pluginMenuButton">
            </ul>
        </div>
    </div>
</div>



    <div class="mobile-tab-nav d-flex justify-content-center d-md-none">
        <div class="sidebar-mobile">
            <button class="mobile-tab-toggle" aria-label="Open menu">
                <i class="fas fa-bars"></i>
            </button>

            <ul class="tabs">
                <li class="tab-link current"
                    data-settingtype="groupinfo"
                    onclick="packagemanager.showManageSettingByType('groupinfo');"
                    style="display:none;">
                    <?php echo $this->user->lang('General'); ?>
                </li>

                <li class="tab-link"
                    data-settingtype="addons"
                    onclick="packagemanager.showManageSettingByType('addons');"
                    style="display:none;">
                    <?php echo $this->user->lang('Package Addons'); ?>
                </li>

                <li class="tab-link"
                    data-settingtype="billing"
                    onclick="packagemanager.showManageSettingByType('billing');"
                    style="display:none;">
                    <?php echo $this->user->lang('Billing'); ?>
                </li>

                <li class="tab-link"
                    data-settingtype="hosting"
                    onclick="packagemanager.showManageSettingByType('hosting');"
                    style="display:none;">
                    <?php echo $this->user->lang('Hosting Account'); ?>
                </li>

                <li class="tab-link"
                    data-settingtype="domaininfo"
                    onclick="packagemanager.showManageSettingByType('domaininfo');"
                    style="display:none;">
                    <?php echo $this->user->lang('Domain Information'); ?>
                </li>

                <li class="tab-link"
                    data-settingtype="domaincontactinfo"
                    onclick="packagemanager.showManageSettingByType('domaincontactinfo');"
                    style="display:none;">
                    <?php echo $this->user->lang('Contact Information'); ?>
                </li>

                <li class="tab-link"
                    data-settingtype="hostrecords"
                    onclick="packagemanager.showManageSettingByType('hostrecords');"
                    style="display:none;">
                    <?php echo $this->user->lang('Host Records'); ?>
                </li>

                <li class="tab-link"
                    data-settingtype="nameservers"
                    onclick="packagemanager.showManageSettingByType('nameservers');"
                    style="display:none;">
                    <?php echo $this->user->lang('Name Servers'); ?>
                </li>

                <li class="tab-link"
                    data-settingtype="certinfo"
                    onclick="packagemanager.showManageSettingByType('certinfo');"
                    style="display:none;">
                    <?php echo $this->user->lang('Certificate Information'); ?>
                </li>

                <?php foreach ($this->product_tab_snapins as $snapin) { ?>
                    <li
                        class="tab-link"
                        data-settingtype="<?php echo $snapin['plugin']; ?>"
                        onclick='packagemanager.showManageSettingByPlugin("index.php?fuse=clients&controller=userprofile&view=productsnapinview&key=<?php echo $snapin['key'];?>&name=<?php echo $snapin['plugin'];?>&id=<?php echo $this->packageid;?>");'>
                        <?php echo $this->user->lang($snapin['title']); ?>
                    </li>
                <?php } ?>
            </ul>
        </div>
    </div>

    <div class="verticalTab">
        <div class="tab-Sidebar">
            <a href="index.php?fuse=clients&controller=userprofile&view=profileproducts">
                <i class="icon-ic-12"></i><?php echo $this->user->lang('Package list'); ?>
            </a>
            <ul class="tabs">
                <li class="tab-link current"
                    data-settingtype="groupinfo"
                    onclick="packagemanager.showManageSettingByType('groupinfo');"
                    style="display:none;">
                    <?php echo $this->user->lang('General'); ?>
                </li>

                <li class="tab-link"
                    data-settingtype="addons"
                    onclick="packagemanager.showManageSettingByType('addons');"
                    style="display:none;">
                    <?php echo $this->user->lang('Package Addons'); ?>
                </li>

                <li class="tab-link"
                    data-settingtype="billing"
                    onclick="packagemanager.showManageSettingByType('billing');"
                    style="display:none;">
                    <?php echo $this->user->lang('Billing'); ?>
                </li>

                <li class="tab-link"
                    data-settingtype="hosting"
                    onclick="packagemanager.showManageSettingByType('hosting');"
                    style="display:none;">
                    <?php echo $this->user->lang('Hosting Account'); ?>
                </li>

                <li class="tab-link"
                    data-settingtype="domaininfo"
                    onclick="packagemanager.showManageSettingByType('domaininfo');"
                    style="display:none;">
                    <?php echo $this->user->lang('Domain Information'); ?>
                </li>

                <li class="tab-link"
                    data-settingtype="domaincontactinfo"
                    onclick="packagemanager.showManageSettingByType('domaincontactinfo');"
                    style="display:none;">
                    <?php echo $this->user->lang('Contact Information'); ?>
                </li>

                <li class="tab-link"
                    data-settingtype="hostrecords"
                    onclick="packagemanager.showManageSettingByType('hostrecords');"
                    style="display:none;">
                    <?php echo $this->user->lang('Host Records'); ?>
                </li>

                <li class="tab-link"
                    data-settingtype="nameservers"
                    onclick="packagemanager.showManageSettingByType('nameservers');"
                    style="display:none;">
                    <?php echo $this->user->lang('Name Servers'); ?>
                </li>

                <li class="tab-link"
                    data-settingtype="certinfo"
                    onclick="packagemanager.showManageSettingByType('certinfo');"
                    style="display:none;">
                    <?php echo $this->user->lang('Certificate Information'); ?>
                </li>

                <?php foreach ($this->product_tab_snapins as $snapin) { ?>
                    <li class="tab-link"
                        data-settingtype="<?php echo $snapin['plugin']; ?>"
                        onclick='packagemanager.showManageSettingByPlugin("index.php?fuse=clients&controller=userprofile&view=productsnapinview&key=<?php echo $snapin['key'];?>&name=<?php echo $snapin['plugin'];?>&id=<?php echo $this->packageid;?>");'>
                        <?php echo $this->user->lang($snapin['title']); ?>
                    </li>
                <?php } ?>
            </ul>

        </div>


        <div id="vtabContent" class="form-wrapper">

            <img id="selectedproductlogo" class="img-fluid" style="display:<?php echo ($this->productinfo['productpluginlogo'] == "") ? "none" : "";?>;" src="<?php echo $this->gRelativePath;?>plugins/<?php echo $this->productinfo['productpluginlogo'];?>" alt="pluginlogo" />

            <div id="accountwarning" class="badge bg-danger mb-3" role="alert"></div>

            <div id="paneldescriptiondiv" style="display:none;" class="alert alert-warning"></div>

            <form id="productsettingsform" action="index.php?fuse=clients&action=adminupdateuserpackage" method="post">
                <input type="hidden" name="settingtype" id="settingtype" />
                <input type="hidden" name="userPackageId" id="userPackageId" value ="<?php echo $this->packageid;?>" />

                <div id="selectedproduct-view"></div>

                <div id="btnoptionsseperator" style="display:none;">
                    <div id="performonserver_wrapper">
                        <label class="checkbox">
                        <input id="performonserver" name="performonserver" type="checkbox" checked="checked" />&nbsp;<span class="labelwithtooltip" data-placement="top" title="<?php echo $this->user->lang('Checking this checkbox will also update the package with the appropriate server plugin.'); ?>"><?php echo $this->user->lang("Update via plugin if necessary"); ?></span>
                        </label>
                    </div>

                    <button id="btnUpdateProduct" type="button" class="cm-btns orange" style="display: none">
                        <?php echo $this->user->lang('Update Package');?>
                    </button>
                    <?php if ($this->user->hasPermission("clients_create_customer_packages")) { ?>
                    <button id="deletepackage" type="button" class="cm-btns dark">
                        <?php echo $this->user->lang('Delete Package');?>
                    </button>

                    <button id="upgradepackage" type="button" class="cm-btns yellow">
                        <?php echo $this->user->lang('Upgrade/Downgrade Package'); ?>
                    </button>
                    <?php } ?>

                </div>

            </form>
            <?php echo $this->unescape($this->customOutput); ?>
        </div>

    </div>
</div>

<script data-cfasync="false">
/**
 * Display Plugin dropdown list if the productData has a plugin
 */
packagemanager.displayPluginOptions = function()
{

    if (packagemanager.paneldescription !== "") {
        $('#paneldescriptiondiv').html(packagemanager.paneldescription).show();
    } else {
        $('#paneldescriptiondiv').hide();
    }

    if ($('#hiddenwarning').length > 0) {
         //let's add to the warning the accountnotonserver
         $('#accountwarning').text($('span[for="hiddenwarning"]').text());
         $('#accountwarning').css('display', 'table');
         $('#performonserver_wrapper').hide();
         $('#performonserver').attr('checked', false);
    } else{
        $('#accountwarning').hide();
    }

    if( packagemanager.hasplugin){
        if( ($('#updateviaplugin').length > 0) && packagemanager.showperformonserver) {

            //Do we add the warning here
            // Change the label on the update package checkbox
            if(packagemanager.producttype == 3) {
                 $('#performonserver_wrapper >span').text('Update at Registrar if necessary');
            } else {
                $('#performonserver_wrapper >span').text($('span[for="updateviaplugin"]').text());
            }
            if(packagemanager.producttype == 2 ) {
                $('#performonserver_wrapper').hide();
            } else {
                $('#performonserver_wrapper').show();
                $('#performonserver').attr('checked', true);
            }
             // Show the hidden domain tabs
             // document.getElementById('settingtype_domaincontactinfo').style.visibility = 'visible';
             // document.getElementById('settingtype_hostrecords').style.visibility = 'visible';
             // document.getElementById('settingtype_nameservers').style.visibility = 'visible';

             $('#performonserver').bind('change',packagemanager.warnaboutsyncing);

        } else {

            $('#performonserver_wrapper').hide();
            $('#performonserver').attr('checked', false);
        }

    } else {
        //no plugin available for this product so let's hide plugin related options
        //check to see if dropdown plugin exists and if so hide it as plugin does not exist
        $('#divpluginactiondropdown').hide();
        $('#performonserver_wrapper').hide();
        $('#performonserver').attr('checked', false);
    }

};

//listener function for type of data being returned for the package
//I need to return some HTML for a field pulled from fields callback
packagemanager.returnFieldHTML = function(data)
{
    var length = 0;

    json = clientexec.parseResponse(data);
    if (json.error) {
        clientexec.unMask();
        return;
    }

    packagemanager.permissions = json.productinfo.Permissions;
    packagemanager.fields = json.productFields;

    // customFields.setColumns('1-wide');
    customFields.load(json.productFields,function(data) {
        $('#selectedproduct-view').append(data);
    }, function(){
        clientexec.postPageLoad('#selectedproduct-view');
        clientexec.unMask();
    });

    // totalActualFields is the number of actaul html fields we are rendering.
    if (json.totalActualFields > 0) {
       //check to see if all fields are disabled... if so remove update btn
        if (customFields.getAllFieldsDisabled()){
            $('#btnUpdateProduct').hide();
            $('#btnoptionsseperator').hide();
        } else {
            $('#btnUpdateProduct').show();
            $('#btnoptionsseperator').show();
        }
    } else {
        $('#selectedproduct-view').append("<div style='clear:both;padding-top:10px;width:400px;color:gray;'><center>" + clientexec.lang('No items found') + "</center></div>");
        $('#btnUpdateProduct').hide();
        $('#btnoptionsseperator').hide();
    }


    //call dispatch function for the newley selected setting panel (if exists)
    var funcName = packagemanager.activeTab+"_dispatch";

    //This if for the js for the dynamic panel
    if (eval("typeof " + funcName + " == 'function'")) {
        eval(funcName+"()");
    }


    $('#productidentifier').text(json.productinfo.name);
    $('#product_desc_details').text(json.productinfo.desc_details);
    packagemanager.displayPluginOptions();

    //update some fields by permission
    //if product added let's update permission
    if ( ($('#productstatus').length > 0) && (!packagemanager.permissions.changestatus) ){
        $('#productstatus').select2('disable');
    }

    if ( ($('#btnUpdateProduct').length > 0) && (!packagemanager.permissions.cansave) ){
        $('#btnUpdateProduct').attr('disabled','true');
    }

    if ( ($('#deletepackage').length > 0) && (!packagemanager.permissions.candelete) ){
        $('#deletepackage').attr('disabled','true');
    }

    if ( ($('#upgradepackage').length > 0) && (!packagemanager.permissions.canupgrade) ){
        $('#upgradepackage').attr('disabled','true');
    }

    //if general let's populate custom fields
    if(packagemanager.activeTab == "groupinfo") {
        packagemanager.toggleProduct();
    }

    $('.quantity').each(function() {
        $(this).keydown(function (e) {
            // Allow: delete, backspace, tab, escape, enter
            if ($.inArray(e.keyCode, [46, 8, 9, 27, 13]) !== -1 ||
                 // Allow: Ctrl+A
                (e.keyCode == 65 && e.ctrlKey === true) ||
                 // Allow: end, home, left, up, right, down
                (e.keyCode >= 35 && e.keyCode <= 40)) {
                     // let it happen, don't do anything
                     return;
            }
            // Ensure that it is a number and stop the keypress
            if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
                e.preventDefault();
            }
        });
    });
};

/**
 * possibly synching issue we should warn about
 */
packagemanager.warnaboutsyncing = function()
{
    if(!$('#performonserver').is(':checked')) {
        $('#serverid').select2('enable', true);
        RichHTML.info("<b style='color:red;'>Warning:</b> You run the risk of unsyncing your product information on Clientexec with the product information on the server.  Only uncheck this option if you know what you are doing.");
    } else {
        $('#serverid').select2('disable', true);
    }
};


$('#deletepackage').on('click', function() {
    packagemanager.deleteProduct();
});

$('#upgradepackage').on('click', function() {
    packagemanager.upgradeProduct();
});

packagemanager.deleteProduct = function()
{
    var pluginadditionalmsg = "";

    if (packagemanager.hasplugin) {
        pluginadditionalmsg = "<br/><br/><div class='alert'>Note: This only deletes the product in Clientexec and does not use the associated plugin.</div>";
    }

    RichHTML.msgBox(
        clientexec.lang('Are you sure you want to delete this package?' + pluginadditionalmsg),
        {
            type:"yesno"
        },
        function(result) {
            if(result.btn === clientexec.lang("Yes")) {
                clientexec.mask();
                $.post(
                    "index.php?fuse=clients&controller=packages&action=admindeletepackages",
                    {
                        ids: packagemanager.package_id
                    },
                    function(data){
                        var json = clientexec.parseResponse(data);

                        if (!json.error) {
                            window.location.href = "index.php?fuse=clients&controller=userprofile&view=profileproducts";
                        }
                    }
                );
            }
        }
    );
};

packagemanager.upgradeProduct = function()
{
    $.post(
        'index.php?fuse=clients&controller=packages&action=getupgradedowngradestatus',
        {
            id: packagemanager.package_id
        },
        function(data){
            var json = clientexec.parseResponse(data);

            if (json.canUpgrade) {
                packagemanager.window.show(
                    {
                        params: {
                            id: packagemanager.package_id
                        }
                    }
                );
            } else {
                if (json.alreadyUpgrading) {
                    RichHTML.alert(
                        json.upgradeMessage,
                        {},
                        function(result){
                            if (result.btn == clientexec.lang('Yes')){
                                $.post(
                                    'index.php?fuse=clients&controller=packages&action=cancelupgradedowngrade',
                                    {
                                        id: packagemanager.package_id
                                    },
                                    function(){
                                        RichHTML.info(clientexec.lang('The package upgrade/downgrade has been canceled'));
                                    }
                                );
                            }
                        }
                    );
                } else {
                    RichHTML.error(json.upgradeMessage);
                }
            }
        }
    );
};

packagemanager.window = new RichHTML.window({
    height: '510',
    width: '840',
    url: 'index.php?fuse=clients&controller=packages&view=upgrade',
    actionUrl: 'index.php?fuse=clients&controller=packages&action=requestupgrade',
    showSubmit: true,
    title: clientexec.lang("Upgrade/Downgrade Package"),
    onSubmit: function(e, data) {
        response = clientexec.parseResponse(e);
        if (!response.error) {
            window.location = 'index.php?fuse=billing&controller=invoice&view=invoice&frmClientID=' + response.clientId + '&invoiceid=' + response.invoiceId + '&profile=1';
        }
    }
});

/**
 * Called when we change the product
 * Note: custom fields are set by group and not product but we retrieve
 * @return void
 */
packagemanager.toggleProduct = function()
{

    //let's remove custom fields
    $('#customfieldsfollow').nextUntil('#customfieldsended').remove();
    $('#customfieldsfollow').remove();
    $('#customfieldsended').remove();
    $('span[for="customfieldsended"]').remove();
    $('span[for="customfieldsfollow"]').remove();

    //let's repoulate the custom fields
    var groupId = $('#subgroup').val();
    $.get('index.php?fuse=clients&action=getproductcustomfields',{
        packageId: packagemanager.package_id,
        groupId: groupId
    },function(xhr){
        if(packagemanager.activeTab == "groupinfo") {
            var json = clientexec.parseResponse(xhr);

            customFields.load(json.productFields,function(data) {
                $('#selectedproduct-view').append(data);
            }, function(){
                clientexec.postPageLoad('.selectedproduct-view');
            });

            clientexec.unMask();
        }

    });
};

/**
 * Method to call when product group is changed
 * @return void
 */
packagemanager.toggleProductGroup = function()
{
    clientexec.mask();
    var groupid = $('#group').val();
    $.get('index.php?fuse=admin&controller=products&action=getproducts',{
        groupid: groupid
    },function(xhr){
        //let's update the product ids
        var json = clientexec.parseResponse(xhr);

        $('#subgroup option').remove();
        $(json.results).each(function(key,obj){
            newoption = $('<option value="'+obj.id+'">'+obj.name+'</option>');
            $('#subgroup').append(newoption);
        });
        $('#select option:first-child').attr("selected", "selected");

        //let's select first item
        $('#subgroup').select2('val',$($('#subgroup option')[0]).val());
        $('#subgroup').change();
    });
};

/**
 * showManageSettingByPlugin description
 *
 * @param  string url Plugin view url
 * @return void
 */
packagemanager.showManageSettingByPlugin = function(url)
{
    location.href = url;
}

/**
* Show settings for the product by a given setting type like billing, hosting, general
*/
packagemanager.showManageSettingByType = function(typeid) {
    packagemanager.updateAvailablePluginActions();
    var url;
    url = "index.php?fuse=clients&controller=userprofile&view=profileproduct&selectedtab="+typeid+"&id="+packagemanager.package_id;
    if ($('#selectedproduct-view').length == 0) {
        location.href = url;
        return;
    }

    clientexec.mask();

    $('.snapin_view').remove();
    $('#btnoptionsseperator').hide();

    //we reset this showperformonserver to true so that we can change based on setting type
    packagemanager.showperformonserver = true;
    packagemanager.paneldescription = "";

    document.getElementById("selectedproduct-view").innerHTML = "";

    $(".vtab").removeClass('active');
    $('#settingtype_'+typeid).addClass("active");
    $('#settingtype').val(typeid);

    packagemanager.activeTab = typeid;

    $.get('index.php?fuse=clients&action=admingetclientproductfields',
        {
            settingtype: typeid,
            packageId: packagemanager.package_id
        },  packagemanager.returnFieldHTML);

    url = "index.php?fuse=clients&controller=userprofile&view=profileproduct&selectedtab="+packagemanager.activeTab+"&id="+packagemanager.package_id;
    History.pushState({}, window.title, url);

};

/**
 * show left tabs based on product type
 * @return void
 */
packagemanager.showlefttabsavailabletoproduct = function ()
{
    for (var i in packagemanager.panels)
    {
        const panel = packagemanager.panels[i];

        /* Show tabs in BOTH menus */
        document
            .querySelectorAll('[data-settingtype="' + panel + '"]')
            .forEach(function (el) {
                el.style.display = '';
            });

        /* Lazy-load JS if needed */
        if ($.inArray(panel, packagemanager.arrayOfLazyLoadingPanels) > -1) {
            clientexec.lazyLoad(
                [relativePath + 'templates/admin/views/clients/packages/sharedjs/profile_product_' + panel + '.js'],
                function () {}
            );
        }
    }
};


/**
 * hide custom field price when needed
 * @return {[type]} [description]
 */
packagemanager.billingChangedCustomPrice = function()
{
    var $customPrice = $('#customprice');
    var $wrapper = $customPrice.closest('.col-sm-6');
    var $label = $('label[for="customprice"]');

    if ($('#usecustomprice').val() === "1") {
        $wrapper.show();
        $label.show();
    } else {
        $wrapper.hide();
        $label.hide();
    }
};

/**
* Toggle recurring billing dropdown
*/
packagemanager.billingToggleRecurring = function()
{
    var idoffirstoption;

    //we need to show an error msg if there are no recurring fees for this product
    if ($('#recurring').val() == "1" && $('#hasRecurringOptions').val() == "0") {
        RichHTML.error("This product type does not have any configured recurring billing cycles.");
    }

    if ($('#recurring').val() == "1") {
        //let's show the billing fields we need with recurring set to 1
        $('#recurring').nextUntil('#btnUpdateProduct',':not(select)').show();
        $('span[for="hiddenwarning"]').hide();

        let idoffirstoption = $('#billingcycle option').eq(0).val();
        if (idoffirstoption == 0 && $('#billingcycle option').length > 1) {
            idoffirstoption = $('#billingcycle option').eq(1).val();
        }

        $('#billingcycle').val(idoffirstoption).trigger('change');

        packagemanager.billingChangedCustomPrice();
    } else {
        //let's show the billing fields we need with recurring set to 1
        $('#selectedproduct-view .col-sm-6').each(function() {
            const hasRecurring = $(this).find('#recurring').length > 0;
            if (!hasRecurring) {
                $(this).hide();  // hide everything except the recurring field container
            } else {
                $(this).show();  // make sure the recurring field stays visible
            }
        });
    }

    //packagemanager.billingChangedBillingCycle();
};

packagemanager.billingChangedBillingCycle = function() {
    RichHTML.info('Changing the Recurring or Billing Cycle of the product can affect its addons.<br>Please make sure to update any active addons after updating the billing information.');
};

/**
 * Update the product
 * @return void
 */
packagemanager.updateactivepanel = function(e)
{

    var valid = $('#productsettingsform').parsley( 'validate' );
    if(!valid) return;

    clientexec.mask();

    // Enable any disabled select fields, so we still pass them with the POST
    var disabledFields = $('#productsettingsform').find('select:disabled').removeAttr('disabled');

    $.ajax({
        type: "POST",
        url: 'index.php?fuse=clients&action=adminupdateuserpackage',
        data: $('#productsettingsform').serializeArray(),
        success: function(xhr){
            var json = clientexec.parseResponse(xhr);

            if (json.error) {
                // Re-disable any select fields since we errored
                disabledFields.attr('disabled','disabled');
                clientexec.unMask();
                return;
            }
            window.location.href = "index.php?fuse=clients&controller=userprofile&view=profileproduct&selectedtab="+packagemanager.activeTab+"&id="+packagemanager.package_id;
        },
        dataType: 'json'
    });
};


//perform a plugin action
/**
 * Perform action on plugin via server call to callpluginaction
 * @param  string pluginaction      action name to call to doaction on plugin
 * @param  string args              additional args to pass for this action
 * @return void
 */
packagemanager.plugincallaction = function(pluginaction,args) {

    //call special methods for actions if they exist
    var funcName = "pluginaction_"+pluginaction;

    if (eval("typeof " + funcName + " == 'function'")) {
        eval(funcName+"()");
    } else {

        //we only want to call if we are not calling another function
        //as that other function will handle when it wants to call the plugin action method
        if (args) {
            args = "";
        }

        if (pluginaction == 'panellogin' || pluginaction == 'panellogin_reseller') {
            packagemanager.plugincallactionpost(pluginaction,args);
            return;
        }

        RichHTML.msgBox(clientexec.lang('Are you sure you want to run the <strong>'+pluginaction+'</strong> action using your plugin?'),
        {type:"yesno"}, function(result) {
            if(result.btn === clientexec.lang("Yes")) {
                packagemanager.plugincallactionpost(pluginaction,args);
            }
        });

    }
};

/**
 * Should only be called only after confirmation box is presented to user confirming plugin action is desired
 * @param  string pluginaction      action name to call to doaction on plugin
 * @param  string args              additional args to pass for this action
 * @return void
 */
packagemanager.plugincallactionpost = function(pluginaction,args)
{
    clientexec.mask();
    $.ajax({
        url: 'index.php?fuse=clients&action=callpluginaction',
        success: function(xhr) {
            var json = clientexec.parseResponse(xhr);
            packagemanager.showManageSettingByType(packagemanager.activeTab);
            packagemanager.updateAvailablePluginActions();
        },
        data: {
            id:packagemanager.package_id,
            actioncmd:pluginaction,
            additionalArgs: args
        }});
};

/**
 * Update the plugin drop down actions
 */
packagemanager.updateAvailablePluginActions = function()
{
    $('#divpluginactiondropdown').hide();
    $.ajax({
        type: 'GET',
        url: 'index.php?fuse=clients&action=getavailablepluginactions',
        data: { id:packagemanager.package_id },
        success: function(xhr) {
            var json = clientexec.parseResponse(xhr);

            $('#plugindropdown li').remove();
            $.each(json.pluginActions,function(index,object){
                $('#plugindropdown').append("<li><a class='dropdown-item' href='#' onclick='packagemanager.plugincallaction(\""+object.cmd+"\");'>"+object.label+"</a></li>");
            });

            if (json.pluginActions.length === 0) {
                $('#divpluginactiondropdown').hide();
            } else {
                $('#divpluginactiondropdown').show();
            }
        },
        dataType: 'json'
    });
};

$(document).ready(function(){
    packagemanager.showlefttabsavailabletoproduct();
    $(".vtab").removeClass('active');

    if (gView == "profileproduct") {
        packagemanager.showManageSettingByType(packagemanager.activeTab);
        $('#btnUpdateProduct').bind('click',packagemanager.updateactivepanel);
    } else {
        //must be a snapin
        $('#product_plugin_'+packagemanager.activeTab).addClass("active");
    }
});

pluginaction_panellogin = function()
{
    $.ajax({
        url: 'index.php?fuse=clients&action=callpluginaction',
        success: function(xhr) {
            var json = clientexec.parseResponse(xhr);
            if (json.success == true) {
                window.open(json.url, '_blank');
            }
        },
        data: {
            id:packagemanager.package_id,
            actioncmd:'panellogin',
        }
    });
}

pluginaction_panellogin_reseller = function()
{
    $.ajax({
        url: 'index.php?fuse=clients&action=callpluginaction',
        success: function(xhr) {
            var json = clientexec.parseResponse(xhr);
            if (json.success == true) {
                window.open(json.url, '_blank');
            }
        },
        data: {
            id:packagemanager.package_id,
            actioncmd:'panellogin_reseller',
            isReseller: true
        }
    });
}
</script>