window.addEvent('domready', function()
{
	//we set an id on all our span:
	var arr_span = $$('#topmenu .firstel a .submenudown');
	for(var i = 0; i < arr_span.length; i++)
		arr_span[i].set('id', Math.random());		
	
	new topmenu($$('#topmenu .firstel'));
});


var topmenu = new Class(
{
	marr_obj_fade: Array(),
	initialize: function(_arr_object)
	{
		//we build our fadein/out object:
		for(var i = 0; i < _arr_object.length; i++)
		{
			//we set an id to our link:
			_arr_object[i].set('id', Math.random());
			var objmenu = this.get_child_by_class(_arr_object[i], 'submenucontainer');

			if (objmenu != null)
			{
				this.marr_obj_fade[i] = {'objfade': new Fx.Tween(objmenu, {'link': 'cancel', duration: 100 }), 'objtrigger': _arr_object[i]};

				//we then set our menu as block, and set it fade out at first:
				objmenu.setStyle('display', 'block');
				this.marr_obj_fade[i].objfade.set('opacity', 0);
			}
			else
				this.marr_obj_fade[i] = null;
		}

		//we set our click event:
		obj_this = this;
		_arr_object.addEvent('mouseenter', function(_evt)
		{
			//we stop our event:
			_evt = new Event(_evt).stop();

			//we fadein our menu:
			obj_this.fadein(true, this);

			//we change our class:
			var objimg = obj_this.get_child_by_class(this, 'submenuup');
			objimg.set('class', 'submenudown');

		});

		_arr_object.addEvent('mouseleave', function(_evt)
		{
			//we stop our event:
			_evt = new Event(_evt).stop();

			//we fadein our menu:
			obj_this.fadein(false, this);

			//we change our class:
			var objimg = obj_this.get_child_by_class(this, 'submenudown');
			objimg.set('class', 'submenuup');
		});
	},
	fadein: function(_bfadein, _obj_trigger)
	{
		//we find our right object:
		

		for(var i = 0; i < this.marr_obj_fade.length; i++)
		{
			if (this.marr_obj_fade[i] != null)
			{
				if (this.marr_obj_fade[i].objtrigger.get('id') == _obj_trigger.get('id'))
				{
					if (_bfadein)
					{
						this.marr_obj_fade[i].objfade.start('opacity', 0, 1);
						return;
					}
					

					this.marr_obj_fade[i].objfade.start('opacity', 1, 0);
					return;
				}
			}
		}
	},
	get_child_by_class: function(_obj, _s_class)
	{
		var arr_children = _obj.getChildren();
		for(var i = 0; i < arr_children.length; i++)
		{
			if (arr_children[i].get('class') == _s_class)
				return arr_children[i];
		}

		for(var i = 0; i < arr_children.length; i++)
		{
			var objtmp = this.get_child_by_class(arr_children[i], _s_class);
			if (objtmp != null)
				return objtmp;
		}

		return null;
	}
});
