/**
* @version   $Id$
* @author    RocketTheme http://www.rockettheme.com
* @copyright Copyright (C) 2007 - 2015 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-navigation'), 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;
					if (child[0]){
						child[0].setStyle('visibility', 'hidden');
					}

					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}).chain(function(){
									fxa.element.setStyle('visibility', 'hidden');
								});
							});
							if (hash['child_item']){
								hash['child_fx'].element.setStyle('visibility', 'visible');
								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.fireEvent('mouseenter');
			}

			if (navigation){
				var child_height = (isActive !== false && groups[isActive]['child_height']) ? groups[isActive]['child_height'] : 0;
				navigation.setStyles({'height': (isActive !== false && groups[isActive]) ? child_height : 0, 'overflow': 'hidden'});
				if (isActive !== false && groups[isActive] && groups[isActive]['child_item']) {
					groups[isActive]['child_fx'].element.setStyle('visibility', 'visible');
					groups[isActive]['child_fx'].set({'opacity': 1});
				}
			}
		}
	};

	window.addEvent('domready', GantrySpliceMenu.init);


})();
