<?php
/**
 * Magento
 *
 * NOTICE OF LICENSE
 *
 * 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 through the world-wide-web at this URL:
 * http://opensource.org/licenses/afl-3.0.php
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@magento.com so we can send you a copy immediately.
 *
 * DISCLAIMER
 *
 * Do not edit or add to this file if you wish to upgrade Magento to newer
 * versions in the future. If you wish to customize Magento for your
 * needs please refer to http://www.magento.com for more information.
 *
 * @category    design
 * @package     default_default
 * @copyright   Copyright (c) 2006-2015 X.commerce, Inc. (http://www.magento.com)
 * @license     http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
 */
?>
<div class="popup-window-mask" id="image-edit-popup-mask" style="display:none"></div>
<div id="advice-container-image" class="advice-container" style="display:none; color: #D40707;"></div>
<div id="image_edit_block" class="image-edit-popup" style="display: none;">

    <div class="image-edit-popup-head" id="image_edit_popup_head"><?php echo $this->__('Edit Image'); ?></div>
    <div class="image-edit-popup-content">

        <div class="action-select">
            <label for="action_type_select"><?php echo $this->__('1. Please select type of the action:'); ?></label>
            <select id="action_type_select" name="action_type_product" class="select" onchange="actionHelper.showActionByType();">
                <option value="product"><?php echo $this->__('Product'); ?></option>
                <option value="cms"><?php echo $this->__('CMS Page'); ?></option>
                <option value="category"><?php echo $this->__('Category'); ?></option>
            </select>
        </div>
        <form name="image_action_form" id="image_action_form">

            <div id="action_selector_cms" class="action">
                <p><?php echo $this->__('2. Please select a page'); ?>:</p>
                <select id="action_type_cms" name="action_type_cms" class="select"">
                    <option value="0"></option>
                    <?php $pages = Mage::getResourceModel('xmlconnect/cms_page_collection')->toOptionIdArray(); ?>
                    <?php if (!count($pages)):?>
                        <option value=""><?php echo $this->__('CMS Pages haven\'t been found.'); ?></option>
                    <?php endif;?>
                    <?php foreach ($pages as $page):?>
                        <option value="<?php echo $page['value']; ?>"><?php echo $page['label']; ?></option>
                    <?php endforeach;?>
                </select>
            </div>

            <div id="action_selector_product" class="action" style="display: none;">
                <span id="xmlconnect_product_search_indicator" class="autocomplete-indicator" style="display: none">
                    <img src="<?php echo $this->getSkinUrl('images/ajax-loader.gif') ?>" alt="<?php echo Mage::helper('core')->quoteEscape($this->__('Loading...')) ?>" class="v-middle"/>
                </span>
                <?php $defProductSearch = $this->__('2. Type Product Name') ?>
                <input id="xmlconnect_product_search" name="query" type="text" class="input-text" value="<?php echo $defProductSearch ?>" onfocus="if(this.value=='<?php echo $defProductSearch ?>')this.value=''; " onblur="if(this.value=='')this.value='<?php echo $defProductSearch ?>';" />
                <div id="xmlconnect_product_search_autocomplete" class="autocomplete"></div>
            </div>

            <div id="action_selector_category" class="action">
                <span id="xmlconnect_category_search_indicator" class="autocomplete-indicator" style="display: none">
                    <img src="<?php echo $this->getSkinUrl('images/ajax-loader.gif') ?>" alt="<?php echo Mage::helper('core')->quoteEscape($this->__('Loading...')) ?>" class="v-middle"/>
                </span>
                <?php $defCategorySearch = $this->__('2. Type Category Name') ?>
                <input id="xmlconnect_category_search" name="query" type="text" class="input-text" value="<?php echo $defCategorySearch ?>" onfocus="if(this.value=='<?php echo $defCategorySearch ?>')this.value=''; " onblur="if(this.value=='')this.value='<?php echo $defCategorySearch ?>';" />
                <div id="xmlconnect_category_search_autocomplete" class="autocomplete"></div>
            </div>

        </form>
    </div>
    <div id="action_edit_image_buttons" class="buttons-set">
        <button type="button" id="action_delete_button" class="scalable delete" onclick="actionHelper.deleteAction();"><span><?php echo $this->__('Delete Action') ?></span></button>
        <button type="submit" id="action_save_button" class="scalable"><span><?php echo $this->__('Save') ?></span></button>
        <button type="button" class="scalable" onclick="actionHelper.closeDialog();"><span><?php echo $this->__('Cancel') ?></span></button>
    </div>
</div>
<script type="text/javascript">
// <![CDATA[
    var actionHelper = {
        currentImage : null,
        actionTypeList : ['product', 'cms', 'category'],
        actionTypePrefixId : 'action_selector_',
        actionSelectorId : 'action_type_select',
        editImageActionBlockId: 'image_edit_block',
        selectedEntityId : null,
        selectedEntityName : null,
        getActionSelectorValue : function() {
            actionSelector = $(this.actionSelectorId);
            return actionSelector.options[actionSelector.selectedIndex].value;
        },
        setActionSelectorValue : function(value) {
            $(this.actionSelectorId).setValue(value);
        },
        showActionByType : function() {
            for (var i = 0; i < this.actionTypeList.length; i++) {
                $(this.actionTypePrefixId + this.actionTypeList[i]).hide();
            }
            $(this.actionTypePrefixId + this.getActionSelectorValue()).show();
        },
        setImageElement : function(element) {
            this.currentImage = element;
        },
        getImageElementConfig : function() {
            if (this.currentImage !== null) {
                return this.currentImage.config;
            } else {
                return null;
            }
        },
        setImageElementConfig : function(image_action_data) {
            this.currentImage.config.image_action_data = image_action_data;
            imageItems.updateEditButtonState(this.currentImage.config);
        },
        saveSelectedAction : function(elem) {
            if ($(elem).hasClassName('disabled')) {
                return
            }
            var data = this.getImageElementConfig();
            for (var i = 0; i < this.actionTypeList.length; i++) {
                if ($(this.actionTypePrefixId + this.actionTypeList[i]).visible()) {
                    data.action_type = this.actionTypeList[i];
                    switch (data.action_type)
                    {
                        case 'product':
                            data.entity_action = this.selectedEntityId;
                            data.entity_name   = this.selectedEntityName;
                            break;
                        case 'cms':
                            var cmsSelector = $('action_type_cms');
                            data.entity_action = cmsSelector.options[cmsSelector.selectedIndex].value;
                            break;
                        case 'category':
                            data.entity_action = this.selectedEntityId;
                            data.entity_name   = this.selectedEntityName;
                            break;
                        default:
                            alert('<?php echo $this->jsQuoteEscape($this->__('Action type does\'t recognized.'));?>');
                            return;
                    }

                    this.sendActionData(data);
                }
            }
        },
        sendActionData : function (data) {
            data.application_id = imageItems.application_id;
            new Ajax.Request('<?php echo $this->getUrl('*/*/saveImageData')?>', {
                parameters: data,
                onSuccess : function(transport) {
                    try {
                        if (transport.responseText.isJSON()) {
                            var response = transport.responseText.evalJSON()
                            if(response.ajaxExpired && response.ajaxRedirect) {
                                setLocation(response.ajaxRedirect);
                            }
                            if (response.error) {
                                alert(response.error);
                            }
                            if (response.success) {
                                actionHelper.setImageElementConfig(response.image_action_data);
                                actionHelper.closeDialog();
                                actionHelper.showAdviceMessage(response.success);
                            }
                        } else {
                            alert(transport.responseText);
                        }
                    } catch (e) {
                        alert(e.message);
                    }
                }
            });
        },
        sendDeleteActionData : function (data) {
            data.application_id = imageItems.application_id;
            new Ajax.Request('<?php echo $this->getUrl('*/*/deleteImageData')?>', {
                parameters: data,
                onSuccess : function(transport) {
                    try {
                        if (transport.responseText.isJSON()) {
                            var response = transport.responseText.evalJSON()
                            if(response.ajaxExpired && response.ajaxRedirect) {
                                setLocation(response.ajaxRedirect);
                            }
                            if (response.error) {
                                alert(response.error);
                            }
                            if (response.success) {
                                actionHelper.setImageElementConfig(response.image_action_data);
                                actionHelper.closeDialog();
                                actionHelper.showAdviceMessage(response.success);
                            }
                        } else {
                            alert(transport.responseText);
                        }
                    } catch (e) {
                        alert(e.message);
                    }
                }
            });
        },
        showAdviceMessage : function (msg) {
            var el = $('advice-container-image').update(msg);
            new Effect.Appear(el, { duration: 1});
            new Effect.Fade(el, { delay: 3, duration: 1 });
        },
        closeDialog : function () {
            this.currentImage = null;
            this.selectedEntityName = this.selectedEntityId = null;
            $('image-edit-popup-mask').hide();
            $(actionHelper.editImageActionBlockId).hide();
            actionHelper.setActionSelectorValue('product');
            $('xmlconnect_product_search').value = '<?php echo $defProductSearch ?>';
        },
        deleteAction : function () {
            var data = this.getImageElementConfig();
            this.sendDeleteActionData(data);
        },
        startDialog : function(element) {
            var actionConfig = actionHelper.getImageElementConfig();
            $('action_save_button').addClassName('disabled');
            if (actionConfig !== null) {
                if (actionConfig.image_action_data !== undefined) {
                    $('image_edit_popup_head').update('<?php echo $this->jsQuoteEscape($this->__('Edit Action')) ?>');
                    $('action_delete_button').show();
                    actionConfig = actionConfig.image_action_data;
                    actionHelper.setActionSelectorValue(actionConfig.action_type);
                    switch (actionConfig.action_type)
                    {
                        case 'product':
                            $('xmlconnect_product_search').value = actionConfig.entity_name;
                            break;
                        case 'cms':
                            $$('#action_type_cms option').each(function(o) {
                                if (o.value == actionConfig.entity_action) {
                                    o.selected = true;
                                    $break;
                                }
                            });
                            break;
                        case 'category':
                            $('xmlconnect_category_search').value = actionConfig.entity_name;
                            break;
                        default:
                            alert('<?php echo $this->jsQuoteEscape($this->__('Action type does\'t recognized.'));?>');
                            return;
                    }
                } else {
                    $('image_edit_popup_head').update('<?php echo $this->jsQuoteEscape($this->__('Add Action')) ?>');
                    $('action_delete_button').hide();
                }
            } else {
                actionHelper.setActionSelectorValue('product');
            }
            actionHelper.showActionByType();
            $('image-edit-popup-mask').setStyle({ height: $('html-body').getHeight() + 'px' }).show();
            $(this.editImageActionBlockId).show();
        }
    }

    new Ajax.Autocompleter('xmlconnect_product_search', 'xmlconnect_product_search_autocomplete',
        '<?php echo $this->getUrl('*/*/globalSearch', array('type' => 'product')) ?>',
        {
            paramName:'query',
            minChars:1,
            indicator:'xmlconnect_product_search_indicator',
            updateElement:getProductSelectionCallback,
            evalJSON:'force'
        }
    );
    function getProductSelectionCallback(li) {
        actionHelper.selectedEntityId = li.getAttribute('id').substring(10);
        $('xmlconnect_product_search').value = actionHelper.selectedEntityName = li.select('p')[0].innerHTML;
        $('action_save_button').removeClassName('disabled');
    }
    function getCategorySelectionCallback(li) {
        actionHelper.selectedEntityId = li.getAttribute('id').substring(10);
        $('xmlconnect_category_search').value = actionHelper.selectedEntityName = li.select('p')[0].innerHTML;
        $('action_save_button').removeClassName('disabled');
    }

    new Ajax.Autocompleter('xmlconnect_category_search', 'xmlconnect_category_search_autocomplete',
        '<?php echo $this->getUrl('*/*/globalSearch', array('type' => 'category')) ?>',
        {
            paramName:'query',
            minChars:1,
            indicator:'xmlconnect_category_search_indicator',
            updateElement:getCategorySelectionCallback,
            evalJSON:'force'
        }
    );

    document.observe('dom:loaded', function () {
        $('action_save_button').observe('click', function () {
            actionHelper.saveSelectedAction(this);
        });

        $('action_type_select').observe('change', function () {
            $('action_save_button').addClassName('disabled');
            $('image_action_form').reset();
        });

        $('action_type_cms').observe('change', function () {
            if ( this.value == 0 ) {
                $('action_save_button').addClassName('disabled');
            } else {
                $('action_save_button').removeClassName('disabled');
            }
        });
    });

//]]>
</script>
