!function ($) {
	$.fn.h6Size = function () {
		$h6 = this;
		$h6.each(function(i) {
			var W = $(this).width()-$(this).find('.toggle-control').width()-$(this).children('b').outerWidth(true)-5;
			$(this).children('span').width(W);
		});
	};
}(window.jQuery);

$(function() {
	// $('.toggle-check').togglebox();
	var $mapTree = $('.map-tree'),
		$mapTreeItem = $mapTree.children('li'),
		$mapItemH6 = $mapTree.find('h6');
	var mapItem = function(w) {
		var WinW = $(window).width(),
			W = null;
		if(WinW < 767) {
			W = w;
		} else {
			W = (w-64)/2;
		};
		return W;
	};
	$('#map-tree-language').css('margin-left',ml = function() {
		var W = null;
		$(this).children('li').map(function(i, v) {
			W -= $(v).width()/2;
		});
		return W;
	});
	$mapTree.each(function(i) {
		$('.line').append("<ul class='line"+(i+1)+" fade'/>");
		if(i < 1) {
			$('.line'+(i+1)).addClass("in active");
		};
		$(this).children('li').each(function(j) {
			$('.line').children('.line'+(i+1)).append("<li/>");
		});
	});
	$mapTreeItem.children('h6').find('span').before(function() {
		var I = ($(this).parents('li').index()+1);
		if (I < 10) {
			I = "0"+I;
		}
		return "<b>" + I + "</b>";
	});
	$mapTreeItem.width(mapItem($mapTree.width()))
	$mapItemH6.h6Size();

	$mapTree.each(function() {
		$(this).masonry({
			itemSelector: '.map-tree > li',
			gutter: 60,
		});
		$(this).masonry('on', 'layoutComplete', function(msnryInstance, laidOutItems) {
			// console.log(msnryInstance.element)
			var element = msnryInstance.element;
			$(element).children('li').children('h6').each(function(i) {
				$('ul.line'+$(element).index()).children('li').eq(i).css('top', ($(this).offset().top-$('ul.line'+$(element).index()).offset().top)+15);
			});
		});
	});
	$mapTree.each(function(j) {
		$(this).children('li').children('h6').each(function(i) {
			$('ul.line'+(j+1)).children('li').eq(i).css('top',($(this).offset().top-$('ul.line'+(j+1)).offset().top)+15);
		});
		$(this).children('li').on('mouseenter', function() {
			$('ul.line'+(j+1)).children('li').eq($(this).index()).css({
				'background-color': '#0088cc',
				'z-index': 1,
			})
		});
		$(this).children('li').on('mouseleave', function() {
			$('ul.line'+(j+1)).children('li').eq($(this).index()).css({
				'background-color': '#DBDBDB',
				'z-index': 0,
			})
		});
	});
	$('#map-tree-language a[data-toggle="tab"]').on('shown', function (e) {
		var target = $(e.target).attr('href');
		// console.log($(target).index())
		$('ul.line'+$(target).index()).addClass("in active").siblings().removeClass("in active");
		$mapTreeItem.width(mapItem($(target).width()))
		// $mapTree.map(function(i,v){
		// 	console.log(v.id +" : " +$(v).width() )
		// })
		$mapItemH6.h6Size();
		$(target).masonry({
			itemSelector: '.map-tree > li',
			gutter: 60,
		});
	});
	$(window).resize(function() {
		var W = null;
		$mapTree.map(function(i,v){
			if($(v).width() > 0) {
				W = $(v).width();
			};
		});
		$mapTreeItem.width(mapItem(W));
		$mapItemH6.h6Size();
	});
});