/*
 * Make a div with id of "species-viewer"
 *
 * Give a <ul> class name of "species-viewer-rollover". The lowercase/underscored
 * versions of the species names are the image file names.
 */
 
var gsRootUri = window.location.pathname.slice( 0, window.location.pathname.lastIndexOf( '/' ) + 1 );
 
/******************************************************************************/
 
Object.extend(String.prototype, {
		trim: function() {
			var s = this;
			while (s.substring(0,1).match( /[ \t\n\r]/ ) ) {
				s = s.substring(1,s.length);
			}
			while (s.substring(s.length-1,s.length).match( /[ \t\n\r]/ ) ) {
				s = s.substring(0,s.length-1);
			}
			return s;
		}
	}
);

/******************************************************************************/
 
var CSpeciesViewer = Class.create();

CSpeciesViewer.prototype = {
	
	initialize: function( oViewer, oList ) {
		$A( oList.childNodes ).each(
			function( oElem, iIdx ) {
				if ( oElem.tagName && oElem.tagName.match( /li/i ) && !Element.hasClassName( oElem, 'ignore' ) ) {
					// Save the color name
					var sColorName = oElem.innerHTML.trim();
					oElem.sColorName = sColorName;
					
					// Save the image file name
					sImageFileName = sColorName.toLowerCase().replace( / /, '_' ) + '.jpg';
					oElem.sImageFileName = sImageFileName;
					
					// Give a reference to the viewer
					oElem.oViewer = oViewer;
					
					// Attach event listeners
					Event.observe( oElem, 'mouseover', this.mouseover.bindAsEventListener( oElem ), false );
				}
			}.bind( this )
		);
	},
	
	mouseover: function( oEvent ) {
		
		// blow away whatever is sitting in the species viewer
		$A( this.oViewer.childNodes ).each(
			function( oElem, iIdx ) {
				this.oViewer.removeChild( oElem );
			}.bind( this )
		);
		
		$A( this.parentNode.childNodes ).each(
			function( oElem, iIdx ) {
				if ( oElem.tagName && oElem.tagName.match( /li/i ) ) {
					oElem.style.backgroundColor = '';
				}
			}
		);
		
		var oImg = document.createElement( 'img' );
		oImg.src = gsRootUri + 'media/images/species/' + this.sImageFileName;
		oImg.alt = this.sColorName;
		
		this.oViewer.appendChild( oImg );
		
		this.style.backgroundColor = 'yellow';
		this.style.position = 'relative';      // IE6 is so astonishingly stupid
	}
	
}

/******************************************************************************/

Event.observe(
	window,
	'load',
	function () {
		new CSpeciesViewer( $( 'species-viewer' ), $( 'species-viewer-rollover' ) );
	},
	false
);
