var BreadCrumb = function (options) {
    this.container = '#breadcrumb-container';
    this.views = new Backbone.Collection();
    

    this.add = function (args) {

        if (!args || typeof args.region == 'undefined' || (!args.region.$el.is('[breadcrumb]') && !args.region.$el.is('[breadcrumb-start]'))) {
            return null;
        }

        args.text = args.region.$el.attr('breadcrumb') ? args.region.$el.attr('breadcrumb') : args.region.$el.attr('breadcrumb-start');
        
        if (args.region.$el.is('[new-breadcrumb]')) {
            this.views.reset();
        }

        if (this.exists(args.region.name)) {
            var regionItem = this.getItem(args.region.name);
            this.selected(null, regionItem);
            return regionItem;
        }

        if (args.region.$el.is('[breadcrumb-level]')) {
            
            var selectedLevel = this.selectLevel(args);

            if (selectedLevel)
                return selectedLevel;
        }

        if (this.views.length > 0 && args.region.$el.is('[final-breadcrumb]')) {
        
            var lastView = this.views.models[this.views.length - 1];
            var region = lastView.get('region');

            if (region.$el.is('[final-breadcrumb]')) {
                this.views.pop();
            }
        }

        var item = this.views.add(args);
        this.render();
        return item;
    };

    this.remove = function(item) {

        if (!this.views) {
            return;
        }

        this.views.remove(item);
        this.render();
    };

    this.removeLast = function() {

        if (!this.views || this.views.length == 0) {
            return;
        }

        this.views.pop();
        this.render();
    };

    this.getItem = function(regionName) {

        if (!this.views || this.views.length == 0) {
            return null;
        }

        var item;

        this.views.each(function (view) {
            var region = view.get('region');

            if (region.name == regionName) {
                item = view.toJSON();
                return false;
            }
        });

        return item;

    };

    this.exists = function (regionName) {

        if (!this.views || this.views.length == 0) {
            return false;
        }

        var exists = false;

        this.views.each(function(view) {
            var region = view.get('region');

            if (region.name == regionName) {
                exists = true;
                return false;
            }
        });

        return exists;
    };

    this.update = function(regionName) {
        
        if (!this.views || this.views.length == 0) {
            return;
        }

        if (!this.exists(regionName)) {
            return;
        }

        for (var i = this.views.models.length - 1; i >= 0; i--) {

            var view = this.views.models[i];

            var region = view.get('region');

            if (region.name == regionName) {
                this.views.remove(view);
            } else {
                break;
            }

        }

        this.render();
    };

    this.render = function() {
        $(this.container).empty();
        $(this.container).show();
        
        if (!this.views) {
            return;
        }

        var self = this;

        var length = this.views.models.length;

        $.each(this.views.models, function (index) {
            this.set('index', index);
            var item = this.toJSON();

            if (index < length - 1) {
                var a = $('<a>', { href: '#', 'class': 'migalha', regionName: item.region.name });
                a.html(item.text);
                a.click($.proxy(self.selected, self, a, item));
                $(self.container).append(a);
            } else {
                $(self.container).append(item.text);
            }
        });

        this.showHideCancelButton();
    };

    this.selected = function(e, args) {

        if (!this.views) {
            return;
        }

        var found = false;

        var item = null;

        while (!found) {

            var currentItem = this.views.pop();

            item = currentItem.toJSON();

            if (item.index == args.index) {
                found = true;
                this.views.add(currentItem);
            } else {
                item.region.$el.hide();

                if (item.controller && item.controller.instance && item.controller.instance.onhide) {
                    item.controller.instance.onhide(currentItem);
                }
            }
        }

        if (item) {
            item.region.$el.show();
            item.controller.instance.currentRegion = item.region;
        }

        this.render();
    };

    this.selectLevel = function(args) {

        if (!args) {
            return null;
        }

        var level = args.region.$el.attr('breadcrumb-level');

        if (!level) {
            return null;
        }
        
        var item = null;
        var exists = false;

        for (var i = this.views.length - 1; i >= 0; i--) {
            var currentItem = this.views.at(i);
            item = currentItem.toJSON();

            var currentLevel = item.region.$el.attr('breadcrumb-level');

            if (currentLevel == level) {
                exists = true;
                break;
            }
        }

        if (!exists) {
            return null;
        }

        var found = false;

        while (!found) {

            var currentItem = this.views.pop();
            item = currentItem.toJSON();

            var currentLevel = item.region.$el.attr('breadcrumb-level');

            if (currentLevel == level) {
                found = true;
                item = this.views.add(args);
            }
        }

        this.render();
        
        return item;
    };

    this.cancel = function() {
        if (!this.views) {
            return;
        }
        var currentItem = this.views.pop();
        currentItem.get('region').$el.hide();
        var currentController = currentItem.get('controller');
        
        if (currentController.instance.onhide) {
            currentController.instance.onhide(currentItem);
        }
        
        if (this.views.length > 0) {
            var item = this.views.models[this.views.length - 1];
            var controller = item.get('controller');
            var region = item.get('region');
            region.$el.show();
            controller.instance.currentRegion = region;
            controller.instance.renderActionButtons();

            if (controller.instance.onshow) {
                controller.instance.onshow(region);
            }
        }

        this.render();
    };

    this.showHideCancelButton = function() {

        if (this.views.length > 1) {

            var lastView = this.views.at(this.views.length - 1);

            var viewController = lastView.get('view') ? lastView.get('view') : lastView.get('controller');
            
            if (typeof viewController.showBreadcrumbCancelButton != 'undefined' && !viewController.showBreadcrumbCancelButton) {
                $('[breadcrumb-cancel]').hide();
            } else {
                $('[breadcrumb-cancel]').show();
            }
            
        } else {
            $('[breadcrumb-cancel]').hide();
        }

    };

    this.attachEvents = function() {
        $('[breadcrumb-cancel]').click($.proxy(this.cancel, this));
    };

    this.hide = function() {
        $(this.container).hide();
    };

    $(document).ready($.proxy(this.attachEvents, this));

};