/**
 * Gestion des liens internes et externes
 * 
 * 
 */
var Links = Class.create({
	initialize: function( options ) {
		this.localdomain = window.location.hostname;
	
	
		this.options = Object.extend({
			externalizeClass	: 'externe',		// Class name for externe link
			noExternalizeClass	: 'no-externe',		// Class name for no externe link
			
			addClassToExterne	: true,				// Add automaticly the class name of externe link
			addClassToNoExterne	: true,				// Add automaticly the class name of no externe link
			
			fireFinishEvent		: true,				// Dispatch a event Links:finished at the end of treatment
			EventName			: 'Links:finished'	// Name of event was dispatched. The event's name must be namespaced with colon (:)
			
		}, options || {} );
		
		this._init();
	},
	
	_init: function() {		
		$$( 'a' ).each( function( a ){
			if( this._isExtern( a ) ) {
				a.observe( 'click', this._onClick.bindAsEventListener(this) );
			}
		}.bind(this));
		
		if( this.options.fireFinishEvent ) {
			$(document).fire( this.options.EventName );
		}
	},
	
	_isExtern: function( link ) {
		if( $(link).hasClassName( this.options.externalizeClass ) ) {
			return true;
		} else if( $(link).hasClassName( this.options.noExternalizeClass ) ) {
			return false;
		}
		
		if( this.localdomain !== link.hostname && ( 'http:' === link.protocol || 'https:' === link.protocol ) ) {
			if( this.options.addClassToExterne ) {
				$(link).addClassName( this.options.externalizeClass );
			}
			
			return true;
		} else {
			if( this.options.addClassToNoExterne ) {
				$(link).addClassName( this.options.noExternalizeClass );
			}
			
			return false;
		}
		
		return false;		
	},
	
	_onClick: function( event ) {
		var a = event.findElement( 'a' );
		
		if( a !== document ) {
			event.stop();
			window.open( a.href );
		}
	}
});

/* Lance les actions lorsque l'arbre du DOM est chargé */
document.observe("dom:loaded", function(e) {
	new Links();
});