/*
---

name: Element.getFavicons

description: Adds a site's favicon to external links on your page

license: MIT-style

requires:
  - Core/Element
  - More/URI
  - More/Assets

provides: [Element.getFavicons]

authors: [Michael Russell]


adaption: replace standard image with favicon
author: delirius

*/

Element.implement({
    getFavicons: function( classNameDiv, imgExtensions ) {
        var baseHost = URI.base.get('host'),
        allDivs = this.getElements( '.'+classNameDiv ),
        imgTypes = imgExtensions || ['ico', 'png', 'gif'];

        allDivs.each( function( el ) {
            var alternateLink = $(el.getElement('a')).get('class').match(/favicon\[(.+)\]/),
            uri = new URI( el.getElement('a') ),
            domain, wrapper;
            if( baseHost != uri.get( 'host' ) ) domain = uri.get('scheme')+'://' + uri.get('host');

            if( alternateLink ){
                el.getElement('img').set('src', alternateLink[1]);
                return;
            } 

            (function( i ){
                var args = arguments,
                favLink = domain +'/favicon.'+ imgTypes[i];
                if( i >= imgTypes.length ) return;

                Asset.image( favLink, {
                    onload:   function() {
                        el.getElement('img').set('src', favLink);
                    },
                    onerror:  function() {
                        args.callee( ++i )
                    }
                });
            })(0)
        });
    }
});

