/****************************************************
 * ExternalLink - jQuery plugin
 *
 *	http://www.zen-in-progress.com/plugin-jquery-externalLink/
 *
 * Copyright (c) 2009 BAREAU Stéphane
 *
 *  Inspired by:
 *     Babylon Design from Samuel Le Morvan (http://www.babylon-design.com/share/faviconize/)
 *
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 *
 ****************************************************/
 (function($) {
  // plugin definition
  $.fn.externalLink = function(options) {
    debug(this);
    var opts = $.extend({}, $.fn.externalLink.defaults, options);
    
    return this.each(function(i,elt) {      
      $this = $(this);
      $this = $this.filter("[href^=\"http\"]");	  
      if( !opts.apply_local)  $this = $this.not("[href*=\""+document.domain+"\"]");
      if( !opts.apply_img)    $this = $this.not(":has(img)");
      if( '' != opts.apply_not)  $this = $this.not("[href*=\""+opts.apply_not+"\"]");	  
	  	  
      $this.each(function()
      {
	    $(this).attr('onClick','window.open(this.href);return false;');
  		var a   = document.createElement('a');
        var img = document.createElement('img');
        if('' != opts.img_class)  $(img).attr('class',opts.img_class);
        if('' != opts.img_title)  $(img).attr('title',opts.img_title);
        if('' != opts.img_alt)    $(img).attr('alt',opts.img_alt);
        if( opts.apply_favicon ) 
        {
          var r   = $(this).attr("href").match(/http:\/\/[a-z0-9.-]*(\/)?/i); 
          r = r[0] + ((r[1] == null) ? "/" : "");         
          $(a).attr('href',r).attr('onClick','window.open(this.href);return false;');
          $(img).attr('src',r+"favicon.ico");

          $(img).error(function()
          {
            $(this).attr('src',opts.default_img);
          });
        }
        else $(img).attr('src',opts.default_img);
        a.appendChild(img);
        if('after'==opts.img_position)        $(this).after($(a));
        else if('before'==opts.img_position)  $(this).before($(a));
      });
    });
  };

  function debug($obj) {
    if (window.console && window.console.log)
      window.console.log('externalLink selection count: ' + $obj.size());
  };

  // plugin defaults
  $.fn.externalLink.defaults = {
      apply_local: true,
      apply_img: true,
      apply_favicon: true,
	  apply_not:'',	  
      img_class:'external',
      img_title:'',
      img_alt:'',
      img_position:'after',
      default_img: './external.gif'
  };

})(jQuery);


