;(function($, window, document, undefined) {
    'use strict';

    window.PageManager = function () {
        return {
            loading: false,
            toggling: {
                'status': [],
                'display_in_menu': []
            },
            filterKey: '',
            pages: [],
            init: function ($ref) {
                var sortable = window.Sortable.create($ref, {
                    animation: 150,
                    draggable:'.nav-stacked-row',
                    handle: '.nav-stacked-drag',
                    filter: '.nav-no-drag',
                    onStart: $.proxy(function (evt) {
                        this.filterKey = '';
                    }, this),
                    onMove: function (evt) {
                        if (! window.canReorder) {
                            return false;
                        }

                        var id = evt.originalEvent.toElement.getAttribute('data-id');
                        if (parseInt(id, 10) === 1 || ! id) {
                            evt.preventDefault();
                            evt.stopPropagation();
                            return false;
                        }
                    },
                    onEnd: $.proxy(function (evt) {
                        if (! window.canReorder) {
                            return false;
                        }

                        if (evt.newDraggableIndex === 0) {
                            return false;
                        }

                        $.ajax({
                            url: window.Pages.reorderUrl,
                            data: window.JSON.stringify(this.getReorderedPositions(sortable.toArray())),
                            method: 'POST',
                            contentType: 'application/json',
                            dataType: 'json',
                            headers: {
                                'X-CSRF-TOKEN': window.Laravel.csrfToken
                            }
                        }).done($.proxy(function (data) {
                            //this.load();
                            window.Ignite.Core.flash('Page order updated successfully.', 'success');
                        }, this)).fail($.proxy(function (error) {
                            window.Ignite.Core.flash('Page order was not updated.', 'error');
                        }, this));
                    }, this)
                });

                this.load();
            },
            load: function () {
                this.loading = true;
                var loader = $.ajax({
                    url: '/admin/cms/pages/api',
                    method: 'GET',
                    dataType: 'json'
                }).fail($.proxy(function (jqXHR, textStatus, errorThrown) {
                    window.Ignite.Core.flash(errorThrown, 'error');
                    this.loading = false;
                }, this)).done($.proxy(function (data) {
                    this.pages = data;
                    this.loading = false;
                }, this));
            },
            filteredPages: function () {
                var filterKey = this.filterKey.length ? this.filterKey.toLowerCase() : '';

                if (filterKey) {
                    return this.pages.filter($.proxy(function (page) {
                        return (page.label.toLowerCase().indexOf(filterKey, 0) !== -1);
                    }, this));
                }

                return this.pages;
            },
            isAlias: function (page) {
                return page['is_alias'];
            },
            isNotAlias: function (page) {
                return ! page['is_alias'];
            },
            isHome: function (page) {
                return page['is_home'];
            },
            editUrl: function (page) {
                return window.Pages.editUrl + '/' + page.id;
            },
            viewUrl: function (page) {
                return window.Laravel.baseUrl + '/' + page.code;
            },
            isActive: function (page) {
                return page.status === 'active';
            },
            isInactive: function (page) {
                return page.status === 'inactive';
            },
            isVisibleInMenu: function (page) {
                return page['display_in_menu'];
            },
            isInvisibleInMenu: function (page) {
                return ! page['display_in_menu'];
            },
            isProtected: function (page) {
                return page['is_protected'];
            },
            publishDate: function (page) {
                return window.moment(page['published_at']).format('MMMM Do YYYY, h:mm:ss a');
            },
            isTogglingStatus: function (page) {
                return this.toggling.status.indexOf(page.id) !== -1;
            },
            toggleStatus: function (page) {
                if (this.isAlias(page) || ! window.canToggleStatus) {
                    return false;
                }

                if (window.confirm('Are you sure you want to toggle the page status?')) {
                    this.toggleAttribute('status', page);
                }
            },
            isTogglingVisibility: function (page) {
                return this.toggling['display_in_menu'].indexOf(page.id) !== -1;
            },
            toggleVisibility: function (page) {
                if (this.isAlias(page) || ! window.canToggleVisibility) {
                    return false;
                }
                if (window.confirm('Are you sure you want to toggle the page visibility?')) {
                    this.toggleAttribute('display_in_menu', page);
                }
            },
            toggleAttribute: function (attribute, page) {
                this.toggling[attribute].push(page.id);

                $.ajax({
                    url: '/admin/cms/pages/api/toggle/' + page.id,
                    method: 'POST',
                    contentType: 'application/json',
                    dataType: 'json',
                    headers: {
                        'X-CSRF-TOKEN': window.Laravel.csrfToken
                    },
                    data: window.JSON.stringify({
                        name: attribute,
                        value: page[attribute]
                    })
                }).fail($.proxy(function (jqXHR, textStatus, errorThrown) {
                    this.toggling[attribute].splice(this.loading[attribute].indexOf(page.id, 1));
                    window.Ignite.Core.flash('Update failed. ' + errorThrown, 'error');
                }, this)).done($.proxy(function (data) {
                    page[attribute] = data.value;
                    this.toggling[attribute].splice(this.toggling[attribute].indexOf(page.id, 1));
                    window.Ignite.Core.flash('Updated successfully.', 'success');
                }, this));
            },
            getReorderedPositions: function (positions) {
                var updates = [];

                $.each(positions, function(index, id) {
                    updates.push({
                        id: id,
                        position: index + 1
                    });
                });

                return updates;
            }
        };
    };

} )(jQuery, window, document);