/*
 * Copyright 2006, John Drinkwater <john@nextraweb.com> http://johndrinkwater.name/
 * Distributed under the terms of the MIT License.
 * A script to add site's favicons to links for each <a href^="http://">
 * If only browsers cached the icons...
 */

if ( typeof addEvent == 'undefined' ) {
	function addEvent( object, type, handler ) {
		if ( object.addEventListener ) {
			object.addEventListener( type, handler, false );
		} else if ( object.attachEvent ) {
			object.attachEvent( [ 'on', type ].join( '' ),handler );
		} else {
			object[ [ 'on', type ].join( '' ) ] = handler;
		}
	}
}

function faviconComplete( ) {

	// Do we want large images? bastard scifi.com has a big one
	if ( this.width && this.width >= 36 )
		return;

	if ( this.link && this.link.style ) {
		this.link.style.backgroundImage = "url( " + this.src+ " )";
		this.link.style.backgroundRepeat = "no-repeat";
		this.link.style.backgroundPosition = "left center";
		this.link.style.paddingLeft = ( this.width + 3 ) + "px";
		// Because some browsers *still* cant do the compound .background (I never said this was going to use setProperty :p)
		//this.link.style.background = "url( " + this.src + " ) no-repeat left center;";
	}
}
function faviconRun() {
	
	if ( !document.getElementsByTagName )
		return;
	var links = document.getElementsByTagName( 'a' );
	var favIcons = new Array(), icons = -1;
	
	for ( var i = 0; i < links.length; i++ ) {

		// IE is stupid
		//if ( links[ i ].offsetParent && links[ i ].offsetParent.parentNode.parentNode.title != document.documentElement.parentNode.title )
		//	continue;

		if ( links[ i ].host && links[ i ].protocol && !links[ i ].host.match( /ezri.nextraweb.com/ ) && !links[ i ].host.match( /johndrinkwater.name/ ) ) {
			
			if ( links[ i ].className && ( links[ i ].className.match( /subtle/ ) || links[ i ].className.match( /nofavicon/ ) ) )
				continue;
			favIcons[ ++icons ] = new Image;
			// Really dumb URI, but this is client side js…
			favIcons[ icons ].src = links[ i ].protocol + '//' + links[ i ].host + "/favicon.ico";
			favIcons[ icons ].link = links[ i ];
			favIcons[ icons ].loaded = faviconComplete;
			favIcons[ icons ].onload = function () { this.loaded( ); };
			// IE claims this is unsupported
			//addEvent( favIcons[ icons ], 'load', function () { this.loaded( ); } );
		}
	}
}

addEvent( window, 'load', faviconRun );
