var NavArrow = {
    // Set the initial parameters
    container: null,
    navArrow: null,
    initialPosition: null,
    linkHash: new Hash(),
    currentOver: null,
    
    // Create the triangle DOM element
    createDOMFragment: function(parentId) {
        var element = $(document.createElement('div'));
        element.addClassName('triangle');
        element.setStyle({
                           display: 'none'
                       });
        $(parentId).appendChild(element);
        return element;
    },
    
    determinePositions: function() {
        var currentSelection = this.container.down('.selected');
        var otherLinks = this.container.down('ul').childElements();
        var counter = 1
        otherLinks.each(function(item) {
            item.id='navlink_'+counter.toString();
            this.linkHash[item.id] = this.getPosition(item);
            counter++;
        }.bind(this));
        this.initialPosition = this.getPosition(currentSelection);
    },
    
    setPosition: function(pos) {
        pos = pos || this.initialPosition;
        this.navArrow.setStyle({
            top: '0px',
            left: pos.toString()+'px'
        });
    },
    
    animatePosition: function(pos) {
        pos= pos || this.initialPosition;
        this.navArrow.morph('left:'+pos.toString()+'px',{ duration: 0.8 })
    },
    
    getPosition: function(e) {
        var positionFromParent = Position.positionedOffset(e).first();
        var selectionWidth = e.getWidth();
        var pos = parseInt(positionFromParent + ((selectionWidth-this.navArrow.getWidth())/2));
        return pos;
    },
    
    prepareEventMonitoring: function() {
        theKeys = this.linkHash.keys();
        theKeys.each(function(el) {
            Event.observe(el,'mouseover', this.repositionTriangleTo.bindAsEventListener(this,el));
        }.bind(this));
        Event.observe(this.container.down('ul'),'mouseout', this.repositionTriangleTo.bindAsEventListener(this))
    },
    
    repositionTriangleTo: function(e,el) {
        Event.stop(e);
        if (el && !(el == this.currentOver)) {
            this.animatePosition(eval('this.linkHash.'+el));
            this.currentOver = el;
        } else {
            this.animatePosition();
            this.currentOver = null;
        }
        
    },
      
    // Initialize the control
    init: function(id) {
        id = id || 'nav';
        if($(id)) {
            this.container = $(id);
            this.navArrow = this.createDOMFragment(id);
            this.determinePositions();
            this.setPosition();
            this.prepareEventMonitoring();
            new Effect.Appear(this.navArrow);
        }
        
    }

};

/*
Event.observe(window, 'load', function() {
   NavArrow.init();
});
*/