function addLoadEvent(func) {
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  } else {
    window.onload = function() {
      oldonload();
      func();
    }
  }
}

function insertAfter(newElement,targetElement) {
  var parent = targetElement.parentNode;
  if (parent.lastChild == targetElement) {
    parent.appendChild(newElement);
  } else {
    parent.insertBefore(newElement,targetElement.nextSibling);
  }
}

function faviconize() { 
   if (!document.getElementsByTagName) return false;
   if (!document.createElement) return false;
   /* get the links on the page */
   var links = document.getElementsByTagName("a");

	/* set hoststring - all urls with href attributes that match hoststring will get icons */
	var hoststring = /^http:/;

	/* for each link found */
	for (var j=0; j<links.length; j++) {

		/* get href attribute value */
		var hrefvalue = links[j].getAttribute("href",2);
		/* get class attribute value */
		var hrefclass = links[j].getAttribute("class");

		/* add the domain(s) to exclude */
	   var localdomain1 = 'addthis.com';
	   var localdomain2 = 'http://www.php.net';
	   var localdomain3 = 'w3.org';
	   var localdomain4 = 'cms.web-seller.co.uk';

		/* if href attribute is found */
		if (hrefvalue) {
			/* if href attribute does not contain localdomain1 */
			if (hrefvalue.search(localdomain1) == -1 && hrefvalue.search(localdomain2) == -1 && hrefvalue.search(localdomain3) == -1 && hrefvalue.search(localdomain4) == -1) {
				var skip1 = false;
			} else { /* if localdomain1 was found in href attribute */
				var skip1 = true;
			}
		}

		/* if href class attribute is set and doesnt contain 'noicon' */
		if (hrefclass && hrefclass.search('noicon') == -1){
			var skip2 = false;
		/* if href class attribute doesnt exist */
		} else if (!hrefclass) {
			var skip2 = false;
		/* if href class attribute exists and contains 'noicon' */
		} else {
			var skip2 = true;
		}

		/* if link has href attribute and attribute contains hoststring (http:) */
		if (hrefvalue && (hrefvalue.search(hoststring) != -1)) {
			var skip3 = false;
		} else {
			var skip3 = true;
		}

		/* if href is not to be skipped for any reason */
		if (skip1!=true && skip2!=true && skip3!=true) {
			var domain = hrefvalue.match(/(\w+):\/\/([^/:]+)(:\d*)?([^# ]*)/);
			domain = RegExp.$2;
			var cue = document.createElement("img");
			cue.className = "faviconimg";
			var cuesrc = "http://"+domain+"/favicon.ico";
			cue.setAttribute("src",cuesrc);
			cue.onerror = function () {
				this.src = "/img/css/external.gif";
			}
			insertAfter(cue,links[j]);
		}
	}
}
addLoadEvent(faviconize);