var legendHighlightClass = "hotspot-highlight";
var svgHightlightClass = "highlight";

$("[data-insert-svg]").each(function( index ) {
	var hotspotId = $(this).attr("data-hotspot-id");
	$(this).after(omd.svgImages[$(this).attr("data-insert-svg")]);
	var svg = $(this).next();
	svg.attr('data-hotspot-id', hotspotId);
    $(this).remove();
});

$("svg").each(function( index ) {
    var svg = Snap(this);

    var tableLegend = $('table[data-legend-id=' + $(this).attr('data-hotspot-id')  + ']');
	
    tableLegend.on("mouseenter", "td:nth-child(odd)", function() {
        setFocus(findSvgElementFromLegendTable($(this)));
        highlightTableEntries($(this));
    });

    tableLegend.on("mouseleave", "td:nth-child(odd)", function() {
        leaveFocus(findSvgElementFromLegendTable($(this)));
        unhighlightTableEntries($(this));
    });

    tableLegend.on("mouseenter", "td:nth-child(even)", function() {
        setFocus(findSvgElementFromLegendTable($(this).prev()));
        highlightTableEntries($(this).prev());
    });
    tableLegend.on("mouseleave", "td:nth-child(even)", function() {
        leaveFocus(findSvgElementFromLegendTable($(this).prev()));
        unhighlightTableEntries($(this).prev());
    });

    $(this).on("mouseenter", "[hotspotid]", function() {
        setFocus(findMatchingSvgElements($(this)));
        highlightTableEntries(findTableEntryForSvgElement($(this)));
    });

    $(this).on("mouseleave", "[hotspotid]", function() {
        leaveFocus(findMatchingSvgElements($(this)));
        unhighlightTableEntries(findTableEntryForSvgElement($(this)));
    });

    function findSvgElementFromLegendTable(leftTableEntry) {
        var ref = leftTableEntry.children()[0].innerHTML;
        return svg.selectAll("*[hotspotid=\"" + ref + "\"]");
    }

    function findMatchingSvgElements(domElement) {
        var ref = domElement.attr("hotspotid");
        return svg.selectAll("*[hotspotid=\"" + ref + "\"]");
    }

    function findTableEntryForSvgElement(domElement) {
        var ref = domElement.attr("hotspotid");
        var entry = tableLegend.find("td:nth-child(odd)").filter(function() {
            return $(this).find("p").text() == ref;
        });
        return entry.first();
    }
});


function setFocus(svgElements) {
  if(!svgElements)
    return;
  svgElements.forEach(function(element) {
    element.addClass(svgHightlightClass);
  });
}

function leaveFocus(svgElements) {
  if(!svgElements)
    return;
  svgElements.forEach(function(element) {
    element.removeClass(svgHightlightClass);
  });
}

function highlightTableEntries(leftTableEntry) {
  if(!leftTableEntry)
    return;
  leftTableEntry.addClass(legendHighlightClass);
  leftTableEntry.next().addClass(legendHighlightClass);
}

function unhighlightTableEntries(leftTableEntry) {
  if(!leftTableEntry)
    return;
  leftTableEntry.removeClass(legendHighlightClass);
  leftTableEntry.next().removeClass(legendHighlightClass);
}


