<?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@magentocommerce.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.magentocommerce.com for more information.
 *
 * @category    design
 * @package     default_default
 * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
 * @license     http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
 */
?>
<?php
/** @var $this Mage_XmlConnect_Block_Adminhtml_Mobile_Edit_Tab_Design_Themes */
/** @var $_themesHelper Mage_XmlConnect_Helper_Theme */
$_themesHelper  = Mage::helper('xmlconnect/theme');
$themeId        = $_themesHelper->getThemeId();
$defaultThemesArray = $_themesHelper->getDefaultThemes();
?>
<tr><td colspan="2"  style="width:540px">
<script type="text/javascript">
// <![CDATA[
var defaultThemes = [];
<?php foreach($defaultThemesArray as $defTheme) : ?>
defaultThemes.push('<?php echo $defTheme->getName(); ?>');
<?php endforeach; ?>

var currentTheme = '<?php echo $themeId; ?>';
var visibleTheme = currentTheme;

if (!window.Magento) {
    var Magento = new Object();
}
Magento.Dropdowns = Class.create();
Magento.Dropdowns.prototype = {
    initialize: function(selector) {
        this.selector   = selector;
        $$('.' + this.selector).each(this.init.bind(this));
        Event.observe(document, 'click', this.hide_all.bind(this,0));
    },

    init: function(el) {
        this.head       = el.down('li.ddtitle');
        this.content    = el.down('li.ddlist');
        this.list       = el.down('ul').childElements();
        this.input      = $(el.id + '_value');

        this.init_items(this.list);
        Event.observe(this.head.down('a'), 'click', this.show.bind(this, this.content));
    },

    init_items: function(list) {
        var that = this;
        list.each(function(i){
            Event.observe(i.down('a'), 'click', function(e){
                e.stop();
                visibleTheme = that.input.value = i.down('a').rel;
                that.hide_all();
                that.head.down('a').innerHTML = i.down('a').innerHTML;
            });
        });
    },

    hide_all: function() {
        $$('.ddlist').each(function(item){
            i = 0;
            if (i == 0 && item.style.display !== 'none') {
                selectActiveTheme();
                i++;
            }
            item.style.display = 'none';
        });
    },

    hide: function(cid) {
        $$('.ddlist').each(function(item){
            if (item.hasClassName('on') && item.id != cid) {
                item.style.display = 'none';
                item.removeClassName('on');
            }
        });
    },

    show: function(c,e) {
        e.stop();
        if (c.hasClassName('on')) {
            Effect.toggle(c, 'blind', { delay: 0.1, duration: .1 });
            c.removeClassName('on');
        } else {
            c.style.display = 'none';
            Effect.toggle(c, 'blind', { delay: 0.1, duration: .1 });
            c.addClassName('on');
        }
    }
};

/**
 * Color field onChange listener
 * handle currentTheme variable
 */
function changeColorListener(id) {
    /**
     * Setting color field correct format for color value
     */
    if ($(id).value == '' || $(id).value == ' ') {
        $(id).value = '_';
    }
    $(id).color.exportColor();
    $('box_' + id).style.background = $(id).value;
}

function selectActiveTheme() {
    currentTheme = visibleTheme;
    mmSetTheme(currentTheme);
}

isNewApplication = <?php echo ($this->isNewApplication() ? "true" : "false"); ?>;
isDefaultThemeLoaded = <?php echo ($this->getDefaultThemeLoaded() ? "true" : "false");?>;
tabDesignWasClicked = false;
dropdownObject = false;

Event.observe(document, 'dom:loaded', function() {
    dropdownObject = new Magento.Dropdowns('dropdown');

    $("mobile_app_tabs_design_section").observe('click', function() {
        if (isNewApplication && !isDefaultThemeLoaded && !tabDesignWasClicked) {
            mmSetTheme(currentTheme);
            createInputHiddenElementThemeLoaded();
            tabDesignWasClicked = true;
        } else if (currentTheme == '<?php echo $_themesHelper->getDefaultThemeName()?>') {
            mmSetTheme(currentTheme);
        }
    });

    $('input_save_as').observe('keypress', function (event) {
        var key = event.which || event.keyCode;
        switch (key) {
            default:
            break;
            case Event.KEY_RETURN:
                saveNewTheme();
            break;
        }
    });

    $('save_as_theme_init').observe('click', function () {
        $('input_save_as').value = '';
        showSaveDialog();
        $('popup-window-mask').setStyle({
            height: $('html-body').getHeight() + 'px'
        });
        Form.Element.focus('input_save_as');
    });

    $('save_as_theme_cancel').observe('click', function () {
        hideSaveDialog();
    });

    $('save_as_theme').observe('click', function () {
        saveNewTheme();
    });

    $('reset_theme').observe('click', function () {
        var disabled = this.hasClassName('disabled');

        if (disabled) {
            return false;
        } else {
            resetThemeChanges();
        };
    });

    $('reset_theme').observe('mouseover', function () {
        $('reset_note').show();
    });

    $('reset_theme').observe('mouseout', function () {
        $('reset_note').hide();
    });

    $('delete_theme').observe('click', function () {
        var disabled = this.hasClassName('disabled');

        if (disabled) {
            return false;
        } else {
            if (confirm('<?php echo $this->__('Are you sure you want to delete this theme? This change will affect all applications.'); ?>')) {
                deleteTheme();
            };
        };
    });

    $('delete_theme').observe('mouseover', function () {
        $('delete_note').show();
    });

    $('delete_theme').observe('mouseout', function () {
        $('delete_note').hide();
    });

});

function showSaveDialog() {
    $('save_as_input_block').show();
};

function hideSaveDialog() {
    $('save_as_input_block').hide();
    $('advice-required-theme-name').hide();
};

function showAdviceMessage (msg) {
    var el = $('advice-container').update(msg);
    new Effect.Appear(el, { duration: 1});
    scrollElementToCenter('scroll_to_id', 800);
    new Effect.Fade(el, { delay: 3, duration: 1 });
};

function getWindowHeight() {
  var body  = document.body;
  var docEl = document.documentElement;
  return window.innerHeight ||
         (docEl && docEl.clientHeight) ||
         (body  && body.clientHeight)  ||
         0;
}

var getScrollRoot = (function() {
  var scrollRoot;
  return function() {
    if (!scrollRoot) {
      var bodyScrollTop  = document.body.scrollTop;
      var docElScrollTop = document.documentElement.scrollTop;
      window.scrollBy(0, 1);
      if (document.body.scrollTop != bodyScrollTop) {
          (scrollRoot = document.body);
      } else {
          (scrollRoot = document.documentElement);
      }
      window.scrollBy(0, -1);
    }
    return scrollRoot;
  };
})();

function interpolate(source,target,pos) {
    return (source + (target - source) * pos);
}
function easing(pos) {
    return (-Math.cos(pos * Math.PI) / 2) + 0.5;
}

function scrollToElement(targetTop, duration) {
    duration || (duration = 1000);
    start = +new Date;
    finish = start + duration;
    startTop = getScrollRoot().scrollTop;
    interval = setInterval(function() {
        var now = +new Date,
        pos = (now > finish) ? 1 : (now - start) / duration;
        var y = interpolate(startTop, targetTop, easing(pos)) >> 0;
        window.scrollTo(0, y);
        if (now > finish) {
            clearInterval(interval);
        }
    }, 10);
}

function scrollElementToCenter(id, duration) {
    var el = $(id);
    var winHeight = getWindowHeight();
    var offsetArray = el.positionedOffset();
    var y = offsetArray[1] - (winHeight / 2);
    scrollToElement(y, duration);
}

function saveTheme() {
    $('input_save_as').value = '';
    if (currentTheme) {
        setThemeSelector(currentTheme);
    }
    saveThemeChanges();
}

function saveNewTheme() {
    if ($('input_save_as').value.replace(/^\s+|\s+$/g,"").length) {
        saveThemeChanges();
    } else {
        $('advice-required-theme-name').appear();
    }
}

function createInputHiddenElementThemeLoaded() {
    inputElement = document.createElement('input');
    inputElement.type = "hidden";
    inputElement.name = "default_theme_loaded";
    inputElement.value = "1";
    $('theme_selector_id_value').parentNode.appendChild(inputElement);
}
mmColorUpdate = false;
mmColorThemes = <?php echo Mage::helper('core')->jsonEncode($this->getAllThemes()); ?>;

function setThemeSelector(theme) {
    $('theme_selector_id_value').setValue(theme);
    $('theme_selector_id_value_flat').setValue(theme);
    toggleButtonsView();
}

function mmSetTheme(theme) {
    if (mmColorThemes[theme]) {
        currentTheme = theme;
        setThemeSelector(theme);
        mmColorUpdate = true;
        for (var key in mmColorThemes[theme]) {
            color2set = mmColorThemes[theme][key];
            $(key).color.fromString(color2set);
            $('box_' + key).style.background = color2set;
        }
        mmColorUpdate = false;
    }
}

function toggleBlock(block,link){
    $$('.' + block + '_cl').each(function(b) {
        if(b.style.display == 'none') {
            b.style.display = 'table-row';
            link.style.backgroundPosition = '0 4px';
        } else {
            b.style.display = 'none';
            link.style.backgroundPosition = '0 -86px';
        }
    });
}

function resetThemeChanges() {
    var actionUrl = '<?php echo $this->getResetThemeActionUrl() ?>';
    currentTheme = visibleTheme;
    new Ajax.Request(actionUrl, {
        parameters: {reset : 1, theme: visibleTheme},
        onSuccess: function(transport) {
            try {
                if (transport.responseText.isJSON()) {
                    var response = transport.responseText.evalJSON()
                } else {
                    var response = eval('(' + transport.responseText + ')');
                }
                message = '';
                if (response) {
                    if(response.ajaxExpired && response.ajaxRedirect) {
                        setLocation(response.ajaxRedirect);
                    }

                    if ((typeof response.error != 'undefined') && (response.error == true)) {
                        message = response.message;
                    } else {
                        mmColorThemes = response;
                        mmSetTheme(currentTheme);
                        message = '<?php echo $this->__('Theme configurations are successfully reset.');?>';
                    }
                } else {
                    message = '<?php echo $this->__('Unknown Error'); ?>';
                }
                showAdviceMessage(message);
            } catch(e) {
                showAdviceMessage(e.message);
            }
        }.bind(this)
    });
}

function saveThemeChanges() {
    newtheme = false;
    if ($('input_save_as').value.replace(/^\s+|\s+$/g,"").length) {
        themeName = $('input_save_as').value;
        newtheme = true
    } else {
        themeName = visibleTheme;
    }

    new Effect.Fade('advice-required-theme-name');

    var actionUrl = "<?php echo $this->getSaveThemeActionUrl() ?>" + 'saveTheme/' + themeName;
    <?php $count = count($_themesHelper->getThemeAjaxParameters()); ?>

    var params = {
        <?php foreach ($_themesHelper->getThemeAjaxParameters() as $name => $id) : ?>
            <?php $count = --$count; echo $name ?> : $('<?php echo $id; ?>').value<?php echo $count ? ',' : ''; ?>
        <?php endforeach; ?>
    };

    if (newtheme) {
        params.newTheme = themeName;
    }

    hideSaveDialog();

    new Ajax.Request(actionUrl, {
        parameters: params,
        onSuccess: function(transport) {
            try {
                if (transport.responseText.isJSON()) {
                    var response = transport.responseText.evalJSON()
                } else {
                    var response = eval('(' + transport.responseText + ')');
                }
                message = '';
                if (response) {
                    if(response.ajaxExpired && response.ajaxRedirect) {
                        setLocation(response.ajaxRedirect);
                    }
                    if ((typeof response.error != 'undefined') && (response.error == true)) {
                        message = response.message;
                    } else {
                        mmColorThemes = response.themes;
                        $('themeSelectorList').update(response.themeSelector);
                        setThemeSelector(response.selectedTheme);

                        if (visibleTheme !== response.selectedTheme) {
                            currentTheme = visibleTheme = response.selectedTheme;
                        }

                        selectActiveTheme();
                        dropdownObject.initialize('dropdown');
                        message = response.message;
                    }
                } else {
                    message = '<?php echo $this->__('Unknown Error.'); ?>';
                }
                showAdviceMessage(message);
            } catch(e) {
                showAdviceMessage(e.message);
            }
        }.bind(this)
    });
}

function deleteTheme() {
    var actionDeleteUrl = "<?php echo $this->getDeleteThemeActionUrl() ?>" + 'theme_id/' + visibleTheme;
    new Ajax.Request(actionDeleteUrl, {
        onSuccess: function(transport) {
            try {
                if (transport.responseText.isJSON()) {
                    var response = transport.responseText.evalJSON()
                } else {
                    var response = eval('(' + transport.responseText + ')');
                }
                message = '';
                if (response) {
                    if ((typeof response.error != 'undefined') && (response.error == true)) {
                        message = response.message;
                    } else {
                        mmColorThemes = response.themes;
                        $('themeSelectorList').update(response.themeSelector);
                        currentTheme = visibleTheme = response.selectedTheme;
                        setThemeSelector(response.selectedTheme);
                        selectActiveTheme();
                        dropdownObject.initialize('dropdown');
                        message = response.message;
                    }
                } else {
                    message = '<?php echo $this->__('Unknown Error.'); ?>';
                }
                showAdviceMessage(message);
            } catch(e) {
                showAdviceMessage(e.message);
            }
        }.bind(this)
    });
}
// ]]>
</script>
    <div id="scroll_to_id" class="theme-select-cont">

        <div class="advice-container" id="advice-container" style="display:none; color: #D40707;"></div>

        <label for="theme_selector_id" class="f-left theme-selector-title"><?php echo $this->__('Preset Theme'); ?></label>

        <div class="no-display">
            <input type="hidden" name="conf[extra][theme]" id="theme_selector_id_value" value="<?php echo $themeId; ?>"/>
            <input type="hidden" name="current_theme" id="theme_selector_id_value_flat" value="<?php echo $themeId; ?>"/>
        </div>

        <div id="themeSelectorList">
            <?php echo $_themesHelper->getThemesSelector(); ?>
        </div>

        <div class="form-buttons" style="float:right">
            <button type="button" class="scalable" id="save_theme" onclick="saveTheme();">
                <span><span><span><?php echo $this->__('Save Theme'); ?></span></span></span>
            </button>
            <button type="button" class="scalable" id="save_as_theme_init">
                <span><span><span><?php echo $this->__('Save As'); ?></span></span></span>
            </button>
        </div>

        <div id="save_as_input_block" style="display:none;">
            <div id="popup-window-mask"></div>
            <div class="popup-theme-save" id="popup-theme-save">
                <h3>Save as...</h3>
                <div class="popup-content">
                    <label for="input_save_as"><?php echo $this->__('Theme label:'); ?></label>
                    <input id="input_save_as" type="text" class="input-text" name="input_save_as" autocomplete="off" value="" />
                    <div class="validation-advice" id="advice-required-theme-name" style="display:none;"><?php echo $this->__('Theme label can\'t be empty'); ?></div>
                    <button type="button" class="scalable save" id="save_as_theme">
                        <span><span><span><?php echo $this->__('Save'); ?></span></span></span>
                    </button>
                    <button type="button" class="scalable" id="save_as_theme_cancel">
                        <span><span><span><?php echo $this->__('Cancel'); ?></span></span></span>
                    </button>
                </div>
            </div>
        </div>

    </div>

</div>
<script type="text/javascript">
//<![CDATA[
document.body.appendChild($('save_as_input_block'));
//]]>
</script>
</td></tr>

<?php
$colorFieldset  = $this->getColorFieldset();
$id2observe     = array();
?>
<?php foreach ($colorFieldset as $set) : ?>
<tr>
    <td colspan="2">
        <h4 class="color-block-heading">
            <a href="javascript:void(0);" onclick="toggleBlock('<?php echo $set['id']; ?>', this);">
                <?php echo $set['label']; ?>
            </a>
        </h4>
    </td>
</tr>
    <?php foreach ($set['fields'] as $field) : ?>
        <tr class="<?php echo $set['id']; ?>_cl">
            <td class="label"><label for="<?php echo $field['id']; ?>"><?php echo $field['label'] ?></label></td>
            <td class="value" style="clear:both;">
                <label class="field_label" for="<?php echo $field['id']; ?>">
                    <span id="box_<?php echo $field['id']; ?>" class="color" style="background:<?php echo $field['value'] ?>;display:block;width:20px;height:20px;">&nbsp;</span>
                </label>
                <input style="background:#fff !important;color:#000 !important;margin:2px 0 0 6px;width:75px;float:left;" autocomplete="off" id="<?php echo $field['id']; ?>" name="<?php echo $field['name'] ?>" value="<?php echo $field['value'] ?>" class=" color {required:false,hash:true} input-text" type="text">
            </td>
        </tr>
        <?php $id2observe[] = $field['id']; ?>
    <?php endforeach; ?>
<?php endforeach; ?>

<tr>
    <td colspan="2">
        <script type="text/javascript">
        //<![CDATA[
                Event.observe(document, 'dom:loaded', function() {

                <?php foreach ($id2observe as $id) : ?>
                    $('<?php echo $id; ?>').observe('change', function() {
                        changeColorListener('<?php echo $id; ?>');
                    });
                <?php endforeach; ?>

                    toggleButtonsView();
                });

                function toggleButtonsView() {
                    var isDefaultThemeActive = false,
                        delete_button = $('delete_theme'),
                        reset_button  = $('reset_theme');

                    for(i = 0; i < defaultThemes.length; i++) {
                        if ($('theme_selector_id_value_flat').value == defaultThemes[i]) {
                            isDefaultThemeActive = true;
                        }
                    }
                    if (isDefaultThemeActive) {
                        delete_button.addClassName('disabled');
                        reset_button.removeClassName('disabled');
                    } else {
                        delete_button.removeClassName('disabled');
                        reset_button.addClassName('disabled');
                    }
                }
        //]]>
        </script>
        <div class="reset-theme">

            <button id="reset_theme" type="button" class="scalable">
                <span><span><span><?php echo $this->__('Reset theme to default'); ?></span></span></span>
            </button>

            <button id="delete_theme" type="button" class="scalable delete">
                <span><span><span><?php echo $this->__('Delete theme'); ?></span></span></span>
            </button>

            <div id="reset_note" style="display:none;"><?php echo $this->__('Only default theme can be reset'); ?></div>
            <div id="delete_note" style="display:none;"><?php echo $this->__('Only custom theme can be deleted'); ?></div>

        </div>
    </td>
</tr>
