<?php
/**
 * OpenMage
 *
 * This source file is subject to the Academic Free License (AFL 3.0)
 * that is bundled with this package in the file LICENSE_AFL.txt.
 * It is also available at https://opensource.org/license/afl-3-0-php
 *
 * @category    design
 * @package     default_default
 * @copyright   Copyright (c) 2006-2020 Magento, Inc. (https://www.magento.com)
 * @copyright   Copyright (c) 2021-2022 The OpenMage Contributors (https://www.openmage.org)
 * @license     https://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
 */
?>
<?php

/**
 * @see Mage_Downloadable_Block_Adminhtml_Catalog_Product_Edit_Tab_Downloadable_Links
 * @var $this Mage_Downloadable_Block_Adminhtml_Catalog_Product_Edit_Tab_Downloadable_Links
 */
?>
<?php $_product = $this->getProduct()?>
<div class="fieldset">
<table cellspacing="0" class="form-list">
    <tbody>
        <tr class="headings">
            <td class="label"><label for="name"><?php echo Mage::helper('downloadable')->__('Title')?></label>
            </td>
            <td class="value">
                <input type="text" class="input-text" id="downloadable_links_title" name="product[links_title]" value="<?php echo $_product->getId() ? $this->escapeHtml($_product->getLinksTitle()) : $this->escapeHtml($this->getLinksTitle()); ?>" <?php echo ($_product->getStoreId() && $this->getUsedDefault())?'disabled="disabled"':'' ?> />
            </td>
            <td class="scope-label"><?php echo !Mage::app()->isSingleStoreMode() ? Mage::helper('adminhtml')->__('[STORE VIEW]') : ''; ?></td>
            <td class="value use-default">
            <?php if($_product->getStoreId()): ?>
                <input id="link_title_default" type="checkbox" name="use_default[]" value="links_title" onclick="toggleValueElements(this, this.parentNode.parentNode)" <?php echo $this->getUsedDefault()?'checked="checked"':'' ?> />
                <label class="normal" for="link_title_default"><?php echo Mage::helper('downloadable')->__('Use Default Value'); ?></label>
            <?php endif ?>
            </td>
        </tr>
    </tbody>
</table>
<br />
<table cellspacing="0" class="form-list">
    <tbody>
        <tr class="headings">
            <td class="label"><label for="name"><?php echo Mage::helper('downloadable')->__('Links can be purchased separately')?></label>
            </td>
            <td class="value">
                    <?php echo $this->getPurchasedSeparatelySelect()?>
                </td>
            <td class="scope-label"><?php echo !Mage::app()->isSingleStoreMode() ? Mage::helper('adminhtml')->__('[GLOBAL]') : ''; ?></td>
            <td><small>&nbsp;</small></td>
        </tr>
    </tbody>
</table>
<br />
<div class="grid">
<div class="hor-scroll">
<table cellspacing="0" class="data border">
    <col width="33%" />
    <col />
    <col />
    <col />
    <col width="1" />
    <col width="1" />
    <col width="1" />
    <col width="1" />
    <thead>
        <tr class="headings">
            <th><?php echo Mage::helper('downloadable')->__('Title')?> <span class="required">*</span></th>
            <?php if ($this->getCanReadPrice() !== false) : ?>
            <th><?php echo Mage::helper('downloadable')->__('Price')?></th>
            <?php endif ?>
            <th><span class="nobr"><?php echo Mage::helper('downloadable')->__('Max. Downloads')?></span></th>
            <th><?php echo Mage::helper('downloadable')->__('Shareable')?></th>
            <th><?php echo Mage::helper('downloadable')->__('Sample')?></th>
            <th><?php echo Mage::helper('downloadable')->__('File')?></th>
            <th><span class="nobr"><?php echo Mage::helper('downloadable')->__('Sort Order')?></span></th>
            <th>&nbsp;</th>
        </tr>
    </thead>
    <tfoot>
        <tr>
            <td colspan="8" class="a-right"><?php echo $this->getAddButtonHtml()?>&nbsp;<?php echo $this->getUploadButtonHtml() ?></td>
        </tr>
    </tfoot>
    <tbody id="link_items_body">
    </tbody>
</table>
<div><small><?php echo Mage::helper('downloadable')->__('Alphanumeric, dash and underscore characters are recommended for filenames. Improper characters are replaced with \'_\'.')?></small></div>
</div>
</div>
</div>

<script type="text/javascript">
//<![CDATA[
var linkTemplate = '<tr id="downloadable_link_{{id}}">'+
    '<td>'+
        '<input type="hidden" class="__delete__" name="downloadable[link][{{id}}][is_delete]" value="" />'+
        '<input type="hidden" name="downloadable[link][{{id}}][link_id]" value="{{link_id}}" />'+
        '<input type="text" class="required-entry input-text" name="downloadable[link][{{id}}][title]" value="{{title}}" />'+
        '<?php echo $_product->getStoreId()?'<input type="checkbox" id="downloadable_link_{{id}}_title" name="downloadable[link][{{id}}][use_default_title]" value="1" /><label class="normal" for="downloadable_link_{{id}}_title">Use Default Value</label>':'' ?>'+
    '</td>'+
    <?php if ($this->getCanReadPrice() !== false) : ?>
    '<td class="input-price">'+
        '<input type="text" id="downloadable_link_{{id}}_price_value" class="input-text validate-number link-prices<?php if ($this->getCanEditPrice() === false) : ?> disabled<?php endif ?>" name="downloadable[link][{{id}}][price]" value="{{price}}"<?php if ($this->getCanEditPrice() === false) : ?> disabled="disabled"<?php endif ?> /> ' +
        '<label>[<?php echo Mage::app()->getStore($_product->getStoreId())->getBaseCurrencyCode() ?>]</label>' +
        <?php if ($_product->getStoreId() && $this->getIsPriceWebsiteScope()) : ?>
        '<br /><input type="checkbox" id="downloadable_link_{{id}}_price" name="downloadable[link][{{id}}][use_default_price]" value="1"<?php if ($this->getCanEditPrice() === false) : ?> disabled="disabled"<?php endif ?> /> <label for="downloadable_link_{{id}}_price">Use Default Value</label>' +
        <?php endif ?>
    '</td>' +
    <?php else: ?>
    '<input type="hidden" id="downloadable_link_{{id}}_price_value" class="link-prices" name="downloadable[link][{{id}}][price]" value="0" />' +
    <?php if ($_product->getStoreId() && $this->getIsPriceWebsiteScope()) : ?>
    '<input type="hidden" id="downloadable_link_{{id}}_price" name="downloadable[link][{{id}}][use_default_price]" value="1" />' +
    <?php endif ?>
    <?php endif ?>
    '<td><input type="text" id="downloadable_link_{{id}}_downloads" name="downloadable[link][{{id}}][number_of_downloads]" class="input-text downloads" value="{{number_of_downloads}}" />'+
    '<p><input type="checkbox" class="checkbox" id="downloadable_link_{{id}}_is_unlimited" name="downloadable[link][{{id}}][is_unlimited]" value="1" {{is_unlimited}} /> <label for="downloadable_link_{{id}}_is_unlimited">Unlimited</label></p></td>'+
    '<td class="a-center">'+
        '<select id="downloadable_link _{{id}}_shareable" name="downloadable[link][{{id}}][is_shareable]">'+
            '<option value="1">Yes</option>'+
            '<option value="0">No</option>'+
            '<option value="2" selected="selected">Use config</option>'+
        '</select>'+
    '</td>'+
    '<td>'+
        '<div class="files">'+
            '<div class="row a-right">'+
                '<label for="downloadable_link_{{id}}_sample_file_type" class="a-left"><input type="radio" class="radio" id="downloadable_link_{{id}}_sample_file_type" name="downloadable[link][{{id}}][sample][type]" value="file"{{sample_file_checked}} /> File:</label>'+
                '<input type="hidden" id="downloadable_link_{{id}}_sample_file_save" name="downloadable[link][{{id}}][sample][file]" value="{{sample_file_save}}" />'+
                '<?php echo $this->getBrowseButtonHtml('sample_'); ?>'+
                '<?php echo $this->getDeleteButtonHtml('sample_'); ?>'+
                '<div id="downloadable_link_{{id}}_sample_file" class="uploader a-left">'+
                    '<div id="downloadable_link_{{id}}_sample_file-old" class="file-row-info"></div>'+
                    '<div id="downloadable_link_{{id}}_sample_file-new" class="file-row-info"></div>'+
                    '<div class="clear"></div>'+
                '</div>'+
            '</div>'+
            '<div class="row">'+
                '<label for="downloadable_link_{{id}}_sample_url_type"><input type="radio" class="radio" id="downloadable_link_{{id}}_sample_url_type" name="downloadable[link][{{id}}][sample][type]" value="url"{{sample_url_checked}} /> URL:</label><input type="text" class="input-text" name="downloadable[link][{{id}}][sample][url]" value="{{sample_url}}" />'+
            '</div>'+
            '<div>'+
                '<span id="downloadable_link_{{id}}_sample_container"></span>'+
            '</div>'+
        '</div>'+
    '</td>'+
    '<td>'+
        '<div class="files">'+
            '<div class="row a-right">'+
                '<label for="downloadable_link_{{id}}_file_type" class="a-left"><input type="radio" class="radio validate-one-required-by-name" id="downloadable_link_{{id}}_file_type" name="downloadable[link][{{id}}][type]" value="file"{{file_checked}} /> File:</label>'+
            '<input type="hidden" class="validate-downloadable-file" id="downloadable_link_{{id}}_file_save" name="downloadable[link][{{id}}][file]" value="{{file_save}}" />'+
                '<?php echo $this->getBrowseButtonHtml(); ?>'+
                '<?php echo $this->getDeleteButtonHtml(); ?>'+
                '<div id="downloadable_link_{{id}}_file" class="uploader a-left">'+
                    '<div id="downloadable_link_{{id}}_file-old" class="file-row-info"></div>'+
                    '<div id="downloadable_link_{{id}}_file-new" class="file-row-info new-file"></div>'+
                    '<div class="clear"></div>'+
                '</div>'+
            '</div>'+
            '<div class="row">'+
                '<label for="downloadable_link_{{id}}_url_type"><input type="radio" class="radio validate-one-required-by-name" id="downloadable_link_{{id}}_url_type" name="downloadable[link][{{id}}][type]" value="url"{{url_checked}} /> URL:</label><input type="text" class="validate-downloadable-url input-text" name="downloadable[link][{{id}}][link_url]" value="{{link_url}}" />'+
            '</div>'+
            '<div>'+
                '<span id="downloadable_link_{{id}}_link_container"></span>'+
            '</div>'+
        '</div>'+
    '</td>'+
    '<td class="a-center"><input type="text" name="downloadable[link][{{id}}][sort_order]" value="{{sort_order}}" class="input-text sort" /></td>'+
    '<td>'+
    '<button id="downloadable_link_{{id}}_delete_button" type="button" class="scalable delete icon-btn delete-link-item"><span><span><span><?php echo $this->jsQuoteEscape(Mage::helper('downloadable')->__('Delete')); ?></span></span></span></button>'+
    '</td>'+
'</tr>';

var linkItems = {
    tbody : $('link_items_body'),
    templateSyntax : /(^|.|\r|\n)({{(\w+)}})/,
    templateText : linkTemplate,
    itemCount : 0,
    add : function(data) {
        alertAlreadyDisplayed = false;
        this.template = new Template(this.templateText, this.templateSyntax);

        if(!data.link_id){
            data = {};
            data.link_id  = 0;
            data.link_type = 'file';
            data.sample_type = 'none';
            data.number_of_downloads = '<?php echo $this->getConfigMaxDownloads() ?>';
        }

        data.id = this.itemCount;

        if (data.link_type == 'url') {
            data.url_checked = ' checked="checked"';
        } else if (data.link_type == 'file') {
            data.file_checked = ' checked="checked"';
        }
        if (data.sample_type == 'url') {
            data.sample_url_checked = ' checked="checked"';
        } else if (data.sample_type == 'file') {
            data.sample_file_checked = ' checked="checked"';
        }

        Element.insert(this.tbody, {'bottom':this.template.evaluate(data)});

        scopeTitle = $('downloadable_link_'+data.id+'_title');
        if (scopeTitle) {
            Event.observe(scopeTitle, 'click', function(event){
                scopeElm = $(Event.findElement(event, 'input'));
                titleField = scopeElm.up(0).down('input[type="text"]');
                if (scopeElm.checked == true) {
                    titleField.disabled = true;
                } else {
                    titleField.disabled = false;
                }
            });
        }
        if (!data.store_title && scopeTitle) {
            scopeTitle.up(0).down('input[type="text"]').disabled = true;
            scopeTitle.checked = true;
        }

        scopePrice = $('downloadable_link_'+data.id+'_price');
        if (scopePrice) {
            Event.observe(scopePrice, 'click', function(event){
                scopeElm = $(Event.findElement(event, 'input'));
                priceField = scopeElm.up(0).down('input[type="text"]');
                if (scopeElm.checked == true) {
                    priceField.disabled = true;
                } else {
                    priceField.disabled = false;
                }
            });
        }
        if (!data.website_price && scopePrice) {
            scopePrice.up(0).down('input[type="text"]').disabled = true;
            scopePrice.checked = true;
        }
        downloadsElm = $('downloadable_link_'+data.id+'_downloads');
        isUnlimitedElm = $('downloadable_link_'+data.id+'_is_unlimited');
        if (data.is_unlimited) {
            downloadsElm.disabled = true;
        }
        Event.observe(isUnlimitedElm, 'click', function(event){
            elm = Event.element(event);
            elm.up('td').down('input[type="text"].downloads').disabled = elm.checked;
        });

        if (data.is_shareable) {
            options = $('downloadable_link _'+data.id+'_shareable').options;
            for (var i=0; i < options.length; i++) {
                if (options[i].value == data.is_shareable) {
                    options[i].selected = true;
                }
            }
        }

        sampleUrl = $('downloadable_link_'+data.id+'_sample_url_type');
        linkUrl = $('downloadable_link_'+data.id+'_url_type');

        if (!data.file_save) {
            data.file_save = [];
        }
        if (!data.sample_file_save) {
            data.sample_file_save = [];
        }
        var UploaderConfigLinkSamples = <?php echo $this->getConfigJson('link_samples') ?>.replace(
            new RegExp('<?php echo $this->getId(); ?>', 'g'),
            'downloadable_link_'+data.id+'_sample_file');

        // link sample file
        new Downloadable.FileUploader(
            'linkssample',
            'linkssample_'+data.id,
            sampleUrl.up('td'),
            'downloadable[link]['+data.id+'][sample]',
            data.sample_file_save,
            'downloadable_link_'+data.id+'_sample_file',
            UploaderConfigLinkSamples
        );

        var UploaderConfigLink = <?php echo $this->getConfigJson() ?>.replace(
            new RegExp('<?php echo $this->getId(); ?>', 'g'),
            'downloadable_link_'+data.id+'_file');
        // link file
        new Downloadable.FileUploader(
            'links',
            'links_'+data.id,
            linkUrl.up('td'),
            'downloadable[link]['+data.id+']',
            data.file_save,
            'downloadable_link_'+data.id+'_file',
            UploaderConfigLink
        );

        linkFile = $('downloadable_link_'+data.id+'_file_type');
        linkFile.advaiceContainer = 'downloadable_link_'+data.id+'_link_container';
        linkUrl.advaiceContainer = 'downloadable_link_'+data.id+'_link_container';
        $('downloadable_link_'+data.id+'_file_save').advaiceContainer = 'downloadable_link_'+data.id+'_link_container';

        sampleFile = $('downloadable_link_'+data.id+'_sample_file_type');

        this.itemCount++;
        this.togglePriceFields();
        this.bindRemoveButtons();

        var inputs = $$('#downloadable_link_' + data.id + ' input');
        inputs.each(function(el) { Event.observe(el, 'change', el.setHasChanges.bind(el));  } )
        var inputs = $$('#downloadable_link_' + data.id + ' button.delete');
        inputs.each(function(el) { Event.observe(el, 'click', el.setHasChanges.bind(el));  } )
    },
    remove : function(event){
        var element = $(Event.findElement(event, 'tr'));
        alertAlreadyDisplayed = false;
        if(element){
            element.down('input[type="hidden"].__delete__').value = '1';
            Element.select(element, 'div.flex').each(function(elm){
                elm.remove();
            });
            element.addClassName('no-display');
            element.addClassName('ignore-validate');
            element.hide();
        }
    },
    bindRemoveButtons : function(){
        var buttons = $$('tbody#link_items_body .delete-link-item');
        for(var i=0;i<buttons.length;i++){
            if(!$(buttons[i]).binded && !$(buttons[i]).hasClassName('disabled')){
                $(buttons[i]).binded = true;
                Event.observe(buttons[i], 'click', this.remove.bind(this));
            }
        }
    },
    togglePriceFields : function(){
        var toogleTo = $('downloadable_link_purchase_type').value;
        var disableFlag = true;
        if (toogleTo == '1') {
            disableFlag = false;
        }
        $$('.link-prices[type="text"]').each(function(elm){
            var flag = disableFlag;
            if (elm.hasClassName('disabled')) {
                flag = true;
            }
            elm.disabled = flag;
        });
    }
}

linkItems.bindRemoveButtons();

if ($('downloadable_link_purchase_type')) {
    Event.observe('downloadable_link_purchase_type', 'change', linkItems.togglePriceFields.bind());
}

if($('add_link_item')) {
    Event.observe('add_link_item', 'click', linkItems.add.bind(linkItems));
}

<?php foreach ($this->getLinkData() as $item): ?>
    linkItems.add(<?php echo $item->toJson()?>);
<?php endforeach ?>

Validation.addAllThese([
    ['validate-downloadable-link-sample-file', 'Please specify File.', function(v,element) {
            fileSaveElm = element.up('div').next('input[type="hidden"]');
            if (element.checked && (fileSaveElm.value == '' || fileSaveElm.value == '[]')) {
                return false;
            }
            return true;
        }]
    ]);
Validation.addAllThese([
    ['validate-downloadable-link-sample-url', 'Please specify Sample URL.', function(v,element) {
            if (element.checked && element.up('p').down('input[type="text"]').value == '') {
                return false;
            }
            return true;
        }]
    ]);
//]]>
</script>
