(function ($) {

$.widget("ui.songArray", {  

    options: {
        pageSize: 12,
        template: 'No template specified', // #song-template
        defaultUrl: null,
        deepLinkPath: '/',
        managerName: null,

        // Selectors
        main: '#main'
    },

    _init: function () {
        var self = this;

        if (this.options.template) {
            if (typeof this.options.template == 'string') {
                this.template = $.template(this.options.template);
            }
            else {
                this.template = this.options.template.template();
            }
        }

        $(this.options.main).bind('update.recipeManager.songArray', function (e, context) {
            var queryParams = $.extend({max: self.options.pageSize}, context),
                url = self.options.defaultUrl + '?' + $.param(queryParams),
                deepLink = self.options.deepLinkPath + '?' + $.param(queryParams);


            $.recipePage(url).then(function (page) {
                page.deepLink = deepLink;

                if (page) {
                    $.tmpl(self.template, page.items()).appendTo(self.element.empty());
                }

                self.page = page;
                self.element.trigger('arrayPageChanged.songArray', [page]);
            });
        });
    },

    destroy: function() {
        $.Widget.prototype.destroy.apply(this, arguments);

        $(this.options.main).unbind('update.recipeManager.songArray');
    },

    nextPage: function() {
        var params = $.extend({}, this.page.linkParams.next);
        this._changeLocation(params);
    },

    prevPage: function() {
        var params = $.extend({}, this.page.linkParams.prev);
        this._changeLocation(params);
    },

    goToPage: function(page) {
        var params = $.extend({}, page.linkParams.self);
        this._changeLocation(params);
    },

    _changeLocation: function (params) {
        $(this.options.main).data(this.options.managerName).changeLocation(params);
    }

});

})(jQuery);

