/**
 * @provides javelin-behavior-repository-crossreference
 * @requires javelin-behavior
 *           javelin-dom
 *           javelin-stratcom
 *           javelin-uri
 */

JX.behavior('repository-crossreference', function(config) {

  // NOTE: Pretty much everything in this file is a worst practice. We're
  // constrained by the markup generated by the syntax highlighters.

  function link(element, lang) {
    JX.DOM.alterClass(element, 'repository-crossreference', true);
    JX.DOM.listen(
      element,
      'click',
      'tag:span',
      function(e) {
        var target = e.getTarget();
        var map = {nc : 'class', nf : 'function', na : null};
        while (target !== document.body) {
          if (JX.DOM.isNode(target, 'span') && (target.className in map)) {
            var timeout = function() {
              if (window.getSelection && !window.getSelection().isCollapsed) {
                return;
              }
              var symbol = target.textContent || target.innerText;
              var query = {
                lang : lang,
                projects : config.projects.join(','),
                jump : true
              };
              if (map[target.className]) {
                query.type = map[target.className];
              }
              if (target.hasAttribute('data-symbol-context')) {
                query.context = target.getAttribute('data-symbol-context');
              }
              if (target.hasAttribute('data-symbol-name')) {
                symbol = target.getAttribute('data-symbol-name');
              }
              var uri = JX.$U('/diffusion/symbol/' + symbol + '/');
              uri.addQueryParams(query);
              window.open(uri);
            };
            setTimeout(timeout, 250);
            e.kill();
            break;
          }
          target = target.parentNode;
        }
      });
  }

  function linkAll(section) {
    var blocks = JX.DOM.scry(document.body, 'div', 'remarkup-code-block');
    for (var i = 0; i < blocks.length; ++i) {
      if (blocks[i].hasAttribute('data-code-lang')) {
        var lang = blocks[i].getAttribute('data-code-lang');
        link(blocks[i], lang);
      }
    }
  }

  if (config.container) {
    link(JX.$(config.container), config.lang);
  } else if (config.section) {
    linkAll(JX.$(config.section));
  }

  JX.Stratcom.listen(
    'differential-preview-update',
    null,
    function(e) {
      linkAll(e.getData().container);
    });

});
