/*globals define*/
/*jslint nomen: true*/

define('de_epages/shop/linkpicker/anchorview', [
    'jquery',
    'backbone',
    '$tmpl!./anchorview',
    '$dict!../dictionary'
], function ($, Backbone, template, dict) {
    'use strict';

    return Backbone.View.extend({

        tagName: 'div',
        template: template,
        events: {
            'change select': '_publishAnchor'
        },

        /**
         * Appends the template to the specified dom node
         * @return {Backbone view}
         */
        render: function (_currentAnchor) {
            var renderedTemplate = this.template({
                currentAnchor: _currentAnchor ? _currentAnchor.replace(/^#/,'') : null,
                anchors: this.anchors
            }).dictParse(dict, true);

            this.$el.empty().append(renderedTemplate);
            $.extend(this, $.tmplItem(renderedTemplate).elements);

            return this;
        },

        /**
         * Sets all provided anchors and rerenders the view to display them
         *
         * @since 6.17.0
         * @param  {String} currentAnchor Anchor that should be pre-selected
         * @param  {Array} anchors       All anchors available
         */
        setAnchors: function (currentAnchor, anchors) {
            this.anchors = anchors;
            this.render(currentAnchor);
        },

        /**
         * Sets select field to 'choose anchor' (placeholder)
         */
        clearLinkData: function () {
            this.$('option').removeAttr('selected');
            this.placeholder.prop('selected', true);
        },

        /**
         * Trigger the 'linkurlchanged' event and publish the link's url
         * @param {Event} _event [Event that was fired]
         * @private
         */
        _publishAnchor: function (_event) {
            this.trigger('anchorselected', $(_event.target).val());
        }
    });
});