$(document).ready(function(){
	var breadcrumb, tab_url, tab_title, tab_img;
	var img_whitelist = [
		'baby','bedding','career_opportunities','checkout','decor','fabric','furniture','gifts','login','my_account','paint','sale','shop_by_room','help'
	];
	var nav_lists = $('.navigationList');

	try{
		breadcrumb = get_toplevel_breadcrumb();
			tab_url		= breadcrumb.url;
			tab_title	= breadcrumb.long_name;
			tab_img		= breadcrumb.short_name;
	}
	catch(e) {
		if (e.code === 'no_links') {
			tab_url		= e.url;
			tab_title	= e.long_name;
			tab_img		= e.short_name;
		}
	}

	if ($.inArray(tab_img, img_whitelist) !== -1) {
		tab_img = '/c.668979/site/leftnav_category_headings/assets/img/' + tab_img + '.gif';							// note: previously located under: /site/left/left_nav_xxx.gif

		var process_nav_list = function(nav_list) {
			var sidebar_children = nav_list.parent().children();
			//if ( (sidebar_children.length > 0) && (sidebar_children[0].tagName.toLowerCase() === 'h6') ) {
			if ( (sidebar_children.length > 0) && ($(sidebar_children[0]).is('h6')) ) {
				return true;
			}
			nav_list.parent().prepend('<h6><a href="' +tab_url+ '"><img src="' +tab_img+ '" alt="' +tab_title+ '" /></a></h6>');
		};
		$.each(nav_lists, function(){
			process_nav_list( $(this) );
		});
	}
});

function get_toplevel_breadcrumb() {
	var container = $('#slb_bread_crumb');
	var result, error;
	if (container.length == 0) {
		error = {
			"code":			"no_crumbs"
		};
		throw( error );
	}
	var first_link = container.find('a.crumb:first');
	if (first_link.length == 0) {
		error = {
			"code":			"no_links",
			"short_name":	$.trim( container.text().toLowerCase() ).replace(/[\r\n]/g,'').replace(/[^a-zA-Z0-9]/g, '_').replace(/_*$/,''),
			"long_name":	$.trim( container.text()               ).replace(/[\r\n]/g,'').replace(/[>\s]*$/,''),
			"url":			document.URL
		};
		throw( error );
	}
	result = {
		"short_name":		$.trim( first_link.text().toLowerCase() ).replace(/[\r\n]/g,'').replace(/[^a-zA-Z0-9]/g, '_'),
		"long_name":		$.trim( first_link.text()               ).replace(/[\r\n]/g,'').replace(/[>\s]*$/,''),
		"url":				first_link.attr('href')
	};
	return result;
}
