/**
 * @version   1.0 January 2, 2012
 * @author    RocketTheme http://www.rockettheme.com
 * @copyright Copyright (C) 2007 - 2012 RocketTheme, LLC
 * @license   http://www.gnu.org/licenses/gpl-2.0.html GNU/GPLv2 only
 */

(function(){
	var GantrySpliceMenu = window.GantrySpliceMenu = {
		init: function(){
			var roots = $$('ul.menutop li'), childs = [], fxs = [], groups = {}, navigation = document.id('rt-subnavigation'), activeRoot;
			var activeArrow = $$('.rt-menubar .arrow-indicator')[0], activeArrowFx;
			var isActive = false;
			
			var s = SpliceMenuSettings;
			
			if (roots.length){
				activeArrowFx = new Fx.Tween(activeArrow, {duration: s.arrow.duration, 'link': 'cancel', transition: s.arrow.transition});
				
				roots.each(function(root, i){
					var cls = root.className.split(' ')[0];
					var child = $$('.parent' + cls);
					
					if (root.hasClass('active')) {
						isActive = cls;
						activeRoot = root;
						activeArrowFx.set('left', root.offsetLeft + root.getSize().x / 2);
					}
					
					child.setStyles({'position': 'absolute', 'display': 'inline-block'});
					if (navigation) navigation.set('tween', {link: 'cancel', duration: s.subpanel.duration, transition: s.subpanel.transition});
					var fx = (child[0]) ? new Fx.Morph(child[0], {link: 'cancel', duration: s.subpanel.duration, transition: s.subpanel.transition}).set({'opacity': 0}) : false;
					groups[cls] = {
						'parent_item': root,
						'child_item': child[0] || false,
						'child_height': (child[0]) ? child[0].getSize().y : false,
						'child_fx': fx
					};
					childs.push(child[0] || false);
					fxs.push(fx);
					
					root.addEvents({
						'mouseenter': function(){
							var hash = groups[cls],
								parent = hash['parent_item'];
								
							fxs.each(function(fxa, j){
								if (j != i && fxa) fxa.start({'opacity': 0});
							});
							if (hash['child_item']) hash['child_fx'].start({'opacity': 1});
							
							if (navigation) navigation.tween('height', hash['child_height'] || 0);
							activeArrowFx.start('left', parent.offsetLeft + parent.getSize().x / 2);
						}
					});
					
				});
			}
			
			if (activeRoot){
				activeRoot.addEvent('leaving', function(){
					//this.fireEvent('mouseenter');
				});
			}
			
			if (navigation){
				navigation.setStyles({'height': groups[isActive]['child_height'] || 0, 'overflow': 'hidden'});
				if (groups[isActive]['child_item']) {
					groups[isActive]['child_fx'].set({'opacity': 1});
				}
			}
		}
	};
	
	window.addEvent('domready', GantrySpliceMenu.init);
	
	
})();
