/*!
 * jQuery breadcrumbs2mbmenu @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.breadcrumbs2mbmenu = function(options){
	
	var settings = $.extend({		
		proxy: document.body,
		closestClass: false, // closestClass: 'li'
		hasChildren: false
	}, options);
	
	return this.each(function(){
		var t = $(this),
			b = $('a', t).toArray(),
			extra = {b: b.slice(), s: 0};
		var tree = $.tree.parse($(settings.proxy), function() {
			var	e = [];
			while (!e.length && extra.b.length) {
				var href = $(extra.b.shift()).attr('href');
				e = $('a[href="'+href+'"]', this);		
				if (e.length) {
					var menu = e.attr('menu');
					if (!menu) {
						menu = e.closest('[menu]').attr('menu');						
					}
					if (menu) {
						return $('#'+menu);
					}
					else {
						break;
					}
				}
				else {
					if (extra.b.length) {
						extra.s++;
					}					
				}
			}
			return []; 	
		}, extra);

		extra = {b: b.slice(extra.s)};
		
		var getClosestElement = settings.closestClass ? function (extra) {
			return $(extra.b.shift()).closest(settings.closestClass);
		} : function (extra) {
			return $(extra.b.shift());
		};
		
		if (settings.hasChildren) {
			tree.each(function(extra){			
				if (!extra.root) {
					extra.root = this;
				}
				else {
					getClosestElement(extra).attr('menu', $(this.element).attr('id'));
				}
			}, null, extra);
		}
		else {			
			$.mbMenu.prototype = $.extend({
				_id_generator: 0
			}, $.mbMenu.prototype); 	
			
			tree.each(function(extra){		
				if (!extra.root) {
					extra.root = this;
				}
				else {
					var id = 'menu_' + $.mbMenu.prototype._id_generator++,
						container =  $(this.element).clone();
					container.attr('id', id);
					$('a', container).removeAttr('menu');
					getClosestElement(extra).attr('menu', id);	
					container.appendTo(document.body).hide();
				}
			}, null, extra);
		}
				
	});	
};

})(jQuery)
);


