define(['Global'],
    function (Global) {
        'use strict';
        var thisView,
            attributes = {
                'data-role': 'collapsible-set',
                'data-collapsed-icon': 'arrow-r',
                'data-expanded-icon': 'arrow-d'
            };
        return Backbone.View.extend({
            tagName: 'div',
            className: 'accordion',
            initialize: function (options) {
                this.options = options || {};
                this.$container = $(options.container);
                this.sections = this.options.sections;
                thisView = this;

                if (options.attributes) {
                    $.extend(attributes, options.attributes);
                }

                this.$el.attr(attributes);
            },
            render: function () {
                this.buildAccordion();
                return this;
            },

            events: {
                'expand .ui-collapsible': 'onExpand',
                'collapse .ui-collapsible': 'onCollapse'
            },

            buildAccordion: function () {
                var defaultState,
					parenthesis = this.options.parenthesis,
					className = !parenthesis ? "ui-btn-up-a  ui-btn-corner-all" : "",
                    span = '<span class="' + className + ' ctn-count">0</span>',
                    ifCount,
                    pieces = "",
                    subtitle;

				span = parenthesis ? ' (' + span + ')' : " " + span;

                $.each(this.sections, function (key, value) {
                    defaultState = value.default && value.default === 'open' ? "data-collapsed='false'" : "";
                    ifCount = value.count ? span : '';
                    subtitle = value.subtitle ? value.subtitle : "";

                    pieces += "<div data-role='collapsible' " + defaultState +
                        " id='" + value.id + "'subtitle='" + subtitle + "'><h3>"
                        + value.title + ifCount + "</h3></div>";
                });

                this.$container.append(
                    this.$el.empty().append(pieces)

                ).trigger('create');

            },

            onExpand: function (e) {
                if (this.options.onExpand)  {
                    this.options.onExpand(e);
                }
            },

            onCollapse: function (e) {
                if (this.options.onCollapse) {
                    this.options.onCollapse(e);
                }
            }
        });
    }
);
