/*!
 * jQuery tree2mbmenu @VERSION
 *
 * Copyright (c) 2011 excentrics.ru
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * Author: Yarovoy Artem (yarovoy at excentrics dot ru)
 *
 * http://www.excentrics.ru
 */

(jQuery.tree && jQuery.mbMenu && (function($){

$.fn.tree2mbmenu = function(options){
	var settings = $.extend({			
		levelPrefix: 'lvl_',
		inheritedPrefix: 'inh_',
		submenuPrefix: 'submenu'		
	}, options);
	
	$.mbMenu.prototype = $.extend({
		_id_generator: 0
	}, $.mbMenu.prototype); 
		
	if (!Array.prototype.map) {
		Array.prototype.map = function(fun /*, thisp*/) {
			var len = this.length;
			if (typeof fun != "function") {
				throw new TypeError();
			}
			var res = new Array(len);
			var thisp = arguments[1];
			for (var i = 0; i < len; i++){
				if (i in this) {
					res[i] = fun.call(thisp, this[i], i, this);
				}
			}
			return res;
		};
	}
	
	return this.each(function(){
		var t = $(this);
		
		var tree = $.tree.parse(t, function() {
			var children = $(this).children();
			while (children.length) {
				var result = children.filter('li');
				if (result.length) {
					return result;
				}
				else {
					children = $(children).children();
				}
			}		
			return [];
		});

		extra = {$submenu: $()};

		tree.each(function(extra){
			var n = this.length, 
				i;
			if (typeof extra.lvl !== 'number') {
				extra.lvl = 0;
				for (i = 0; i < n; i++) {
					$(this[i].element).addClass('rootVoice');
				}	
			}
			else {
				extra.lvl++;
				var id = 'menu_' + $.mbMenu.prototype._id_generator++,
					e = $(this.element);
				this.a = e.children().filter('a');
				if (n) {
					this.container = $('<div id="'+id+'"/>');
					if (extra.lvl > 1) {
						this.a.attr('menu', id);
					}
					else {
						e.attr('menu', id);
					}					
					this.container.appendTo(document.body).hide();
					
					
					extra.$submenu = extra.$submenu.add(this.container);
				}
				else
				{
					e.attr('menu', 'empty');
				}	
				this.a.addClass(settings.levelPrefix + extra.lvl).addClass(e.attr('class').split().map(function(i){
					return settings.inheritedPrefix + i;
				}).join());
			}
		},
		function(extra){
			if (extra.lvl > 1) {				
				this.parent().container.append(this.a.detach());
				$(this.element).detach();				
			}
			else if (extra.lvl) {
				$('ul', this.element).detach();				
			}
			extra.lvl--;
		}, extra);		
		
		$('a:first', extra.$submenu).addClass('first-element');
		$('a:last', extra.$submenu).addClass('last-element');
		extra.$submenu.children().filter('a').addClass(settings.submenuPrefix);
	});
	
};

})(jQuery)
);


