var TopicsContextualLinks = function() {
  // Since this is served from topics, we know the index url which works as our base
  var base_url = 'http://topics.latimes.com/';
  var section = null;

  var iframe = null;

  // where the content we're going to parse resides
  var content_div = null;
  // where the related topics lives
  var related_div = null;
  var on_load_function = null;
  var count = 6;
  // passing url so we can cache the results
  var post_url = base_url + "topics/topics_in_text/" + window.location.hostname + window.location.pathname;
  if (post_url.search('.html$') == -1) {
    post_url = post_url + ".html"
  }


  // add a couple of useful methods normally added by prototype
  if (!Array.prototype.each) {
    Array.prototype.each = function(f) {for(var i=0;i<this.length;i++){f(this[i]);}};
  }

  function doOnLoad(element, funct) {
    if (element.addEventListener) {
      element.addEventListener('load', funct, false);
    } else {
      element.attachEvent('onload', funct);
    }
  }

  function removeOnLoad(element, funct) {
    if (element.removeEventListener) {
      element.removeEventListener('load', funct, false);
    } else {
      element.detachEvent('onload', funct);
    }
  }

  function loadData() {
    var topics = getData();
    if (topics.length > 0) {
      embedLinks(content_div, topics);
      if (related_div) relatedTopics(related_div, count, topics, false);
    } else if (related_div) {
      // no data but need to load popular topics
      doOnLoad(iframe, function() {
        var hot_topics = getData();
        relatedTopics(related_div, count, hot_topics, true);
      });
      iframe.contentWindow.location.replace(base_url + "topics/hot_topics");
    }
  }

  function getData() {
    ret = [];
    data = iframe.contentWindow.topics;
    if (data) {
      for (var i = 0, length = data.length; i < length; i++)
        ret.push(data[i]);
    }
    return ret;
  }

  function iframe_document(iframe) {
    var iframedoc;
    if (iframe.contentDocument) {
      // For NS6
      iframedoc = iframe.contentDocument; 
    } else if (iframe.contentWindow) {
      // For IE5.5 and IE6
      iframedoc = iframe.contentWindow.document;
    } else if (iframe.document) {
      // For IE5
      iframedoc = iframe.document;
    }
    return iframedoc;
  }

  function embedLinks(text_div, topics) {
    var node = text_div;
    if (node == null) return;
    topics.each(function(topic) {
      regex = "(^|[^\\w])" + topic.name.replace(/ /g, '\\s') + "([^\\w]|$)";
      doEmbedLinks(node, topic, regex);
    });
  }

  function doEmbedLinks(node, topic, regex) {
    if (node.nodeName.toLowerCase() == 'a') {
      // ignore links
    }
    else if (node.nodeName == "#text") { // text
      if ((index = node.nodeValue.search(regex)) > -1) {
        // don't want to get first \w character
        if (node.nodeValue.charAt(index).search(/\s/) == 0) index++;
        node = node.splitText(index + topic.name.length).previousSibling;
        node = node.splitText(index).previousSibling;
        nameNode = node.nextSibling;
        linkNode = document.createElement("a");
        linkNode.setAttribute("href", topic.url);
        linkNode.setAttribute("class", "contextual_link");
        nameNode.parentNode.replaceChild(linkNode, nameNode);
        linkNode.appendChild(nameNode);
        return true;
      }
    }
    else if (node.childNodes) {
      node = node.childNodes[0];
      while (node) {
        if (doEmbedLinks(node, topic, regex)) return true;
        node = node.nextSibling;
        // using nextSibling because the childNode list will grow 
        // from the use of splitText above -- we want to get everything!
      }
    }
    return false;
  }

  function relatedTopics(div, count, topics, hot) {
    if (div == null) return;
    if (!count) count = 4;
    var matchesHTML;
    if (hot) {
      matchesHTML = '<h2>Popular Topics</h2>';
    } else {
      matchesHTML = '<h2>Related Topics</h2>';
    }
    matchesHTML += '<div class="content"><ul id="related_topics_list">';
    to_show = new Array();
    // don't show topics without a photo
    topics.each(function(t) { if (t.photo_url) to_show.push(t) });
    if (to_show.length < count) count = to_show.length;
    for (var i = 0; i < count; i++) {
      matchesHTML += createTopicLink(to_show[i]);
    }
    matchesHTML += '</ul><div class="clear_left">&nbsp;</div></div>';
    div.innerHTML = matchesHTML;
    document.getElementById('related_topics_list').className = getLayoutName(count);
  }

  function createTopicLink(topic) {
    var html = "<li>";
    html += "<a href='"+topic.url+"'><img src='"+topic.photo_url+"' height='75' width='100'/></a><br/>";
    // re-replace \s in the name
    var name = topic.name.replace(/\\s/g," ");
    html += "<a href='"+topic.url+"'>"+name+"</a></li>";				
    return html;
  }

  function getLayoutName(elements) {
     switch (elements) {
     case 1: result = 'half'; break;
     case 2: result = 'half'; break;
     case 4: result = 'half'; break;
     default: result = 'third';
     }
     return result;
  }

  // public methods
  return {
    link_topics_on_load: function(text_div, topics_div, count, section) {
      doOnLoad(window, function() { TopicsContextualLinks.topics_links(text_div, topics_div, count, section) });
    },

    topics_links: function(text_div, topics_div, size, topic_section) {
      section = topic_section;
      count = size;
      content_div = document.getElementById(text_div);
      if (content_div == null) return;
      related_div = document.getElementById(topics_div);
      document.domain = "latimes.com";
      iframe = document.createElement("iframe");
      iframe.id = "CLIFrame";
      iframe.style.visibility = "hidden";
      iframe = document.body.appendChild(iframe);

      on_load_function = function() {
        removeOnLoad(iframe, on_load_function);
        iframedoc = iframe_document(iframe);

        if ((iframe.contentWindow.topics.length > 0) || 
            iframe.contentWindow.post) {
          // data was cached
          loadData();
          return;
        }
        
        var form = iframedoc.createElement("form");
        form.action = post_url;
        form.method = "POST";
        var field = iframedoc.createElement("input");
        field.type = "text";
        field.name = "text";
        field.value = escape(content_div.innerHTML);
        field = form.appendChild(field);
        form = iframedoc.body.appendChild(form);

        on_load_function = function() {
          removeOnLoad(iframe, on_load_function);
          loadData();
        };
        doOnLoad(iframe, on_load_function);

        form.submit();
        // doing this here because FF doesn't work otherwise for some reason
        iframe.setAttribute("style", "display:none; visibility:hidden; width:0px; height:0px; border:0px;");
      };

      iframe = document.body.appendChild(iframe);

      doOnLoad(iframe, on_load_function);

      iframe.contentWindow.location.replace(post_url);
    }

  };
}();




var topics_div;
var count;

function relatedTopics(text, div, c) {
  topics_div = div;
  count = c;
}

function embedLinks(text_div) {
  TopicsContextualLinks.topics_links(text_div, topics_div, count)
}
