if (typeof HTMLElement != "undefined") {
    if (HTMLElement.prototype.__defineGetter__) {
        HTMLElement.prototype.__defineGetter__("innerText", 
                    function () { return(this.textContent); });
        HTMLElement.prototype.__defineSetter__("innerText", 
                    function (txt) { this.textContent = txt; });
    }
}

var URL = "http://www.thefind.com/query.php";
var gNewWindow = true;
var gLinkColor = "orange";	/// TODO: use hex triplets for color values
var TRIGGER_TAG_NAME = "A";
var TRIGGER_IMG = "IMG";
var TRIGGER_HREF = "http://www.thefind.com";
var gCobrand = "";

function tf_getQueryStringParams()
{
  var src = null;
  var scripts = document.getElementsByTagName("SCRIPT");
  for (var i = 0; i < scripts.length; i++) {
	  var script = scripts[i];
	  if (script.src && (script.src.indexOf("shoplinks.js") >=0)) {
	    src = script.src;
	    break;
	  }
  }
    
  if (src) {
	  var qs = src.substr(src.indexOf('?') + 1);
	  var pairs = qs.split('&');
	  var params = {};
	  for (var i = 0; i < pairs.length; i++) {
	    var keyvalue = pairs[i].split('=');
	    params[keyvalue[0]] = keyvalue[1];
	  }
	  return params;
  }
  return null;
}

function tf_init() {
  var params = tf_getQueryStringParams();
  var cobrand = params.cobrand || "";
  var color = params.color;
  if (cobrand)
    gCobrand = cobrand;
  if (color)
	  gLinkColor = color;
  URL += "?cobrand=" + cobrand;
}

function tf_getInnerContent(obj, html){
  if(html) {
    return obj.innerHTML;
  } else {
    if (obj.innerText) {
        return obj.innerText;
    } else if (obj.textContent) {
        return obj.textContent;
    } else {
      // If there an child IMG nodes, alter the search query
      for (var j=0; j < obj.childNodes.length; j++) {
        if (obj.childNodes[j].tagName == TRIGGER_IMG) {
          var image = obj.childNodes[j];
          return image.title || image.alt;
        }
      }
    }
  }
}

function tf_shoplinks(element) {
  /**
   * Loop through all the <A> tags, and the <IMG> tags within the <A> tags.
   * For each, if the search term can be found in the <IMG> tag, use it.
   * If not, get from the <A> tag.
   */
  var ignoreList = new Array('thefind.com', 'www.thefind.com', 'thefind', 'the find', 'powered by thefind.com', 'powered by thefind');
  var elems = element.getElementsByTagName(TRIGGER_TAG_NAME);
  
  for (var i = 0; i < elems.length; i++) {
    var elem = elems[i];
    
    // only process the hrefs containing thefind.com
    if (elem.href.match(/\:\/\/(www.)?thefind.com\/?$/i)) {
      var innerContent = tf_getInnerContent(elem, false);
      /**
       * Process flow:
       * Step 1 - Check the ignore list.
       * Step 2 - Set the query based on the A HREF inner content 
       */
      if (innerContent) {
        var ignoreFlag = false;
        for (var j=0; j<ignoreList.length; j++) {
          var ignore = ignoreList[j];
          if (ignore == innerContent.toLowerCase()) {
            ignoreFlag = true;
            continue;
          }
        }
        if (ignoreFlag) {
          continue;
        }
      }
      
      var query = elem.title || innerContent;
      
      // If query found, alter the tag
      if (query) {
        query = query.replace(/^\s+|\s+$/g,"");
        if ( (query != "") && (query != null) ) {
          var queryEncoded = encodeURIComponent(query).replace(/%20/g, "+");
          elem.title = "Find this item at thefind.com";
          elem.href = URL + '&query=' + queryEncoded + '&cm_mmc=syndication-_-' + gCobrand + '-_-shopLink-_-' + queryEncoded;
          if (gNewWindow) {
            elem.target = "thefind_preview";
          }
          if (gLinkColor != "none") {
            if (elem.style.color) {
              elem.style.color = "inherit";
            }
          }
          elem.style.textDecoration = "underline";
          elem.style.cursor = "pointer";

          // If there an child IMG nodes, add a bordera 
          for (var j=0; j < elem.childNodes.length; j++) {
            if (elem.childNodes[j].tagName == TRIGGER_IMG) {
              var image = elem.childNodes[j];
              if ( (query != "") && (query != null) ) {
               image.style.borderWidth = "1px";
               image.style.borderStyle = "dotted";
               if (gLinkColor != "none")
                 image.style.borderColor = gLinkColor;
              }
            }
          }
        }
      }
    }
  }
}

if (window.addEventListener) {
    window.addEventListener("load", function() {
    	tf_init();
    	tf_shoplinks(document);
    }, false);
}
if (window.attachEvent) {
    window.attachEvent("onload", function() {
    	tf_init();
    	tf_shoplinks(document);
    }, false);
}
