(
	/**
		(BSD License) 100% Open Source see http://en.wikipedia.org/wiki/BSD_licenses
		
		Copyright (c) 2009, Martin Heidegger
		All rights reserved.
		
		Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
		
		    * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
		    * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
		    * Neither the name of the Martin Heidegger nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
		
		THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
		
		@version 1.1
	*/
	function ( scope )
	{
		if( null == scope.at ) scope.at = {};
		if( null == scope.at.leichtgewicht ) scope.at.leichtgewicht = {};
		if( null == scope.at.leichtgewicht.color ) scope.at.leichtgewicht.color = {};
		
		// classpath = at.leichtgewicht
		var classPath = scope.at.leichtgewicht.color;
		var statik;
		var publik;
		
		
		/**
		 * ColorFade
		 * The color fade class helps to fade a color over time. You can use it to change a color over time
		 * The passed in property object contains
		 *     - cycle [Number] Time in milliseconds which it takes to fullfill a cycle
		 *     - saturation [Number] Saturation of the color
		 *     - brightness [Number] Brightness of the color
		 *     - rules[Object] rules that should be replaced
		 * 
		 * @param properties [Object] object to pass in the properties example:
		*                                      { saturation: 0.4, brightness: 0.3, cycle: 3000, rules:{"h1":["color"]}
		 */
		statik = classPath.ColorFade = function( properties )
		{
			this.statik.initMouseDownHandle();
			this.replacer = new classPath.ColorReplacer( properties.rules );
			this.properties = properties;
			var scope = this;
			setInterval(function() {
					scope.onInterval();
			}, document.all?1000:80);
			// Immediate execution
			this.onInterval();
 	 	};
		// Static on mousedown handler - IE doesn't like changes on links
		statik.mouseDown = false;
		/**
		 * Static internal util to handle a mousedown bug in Internet Explorer
		 */
		statik.initMouseDownHandle = function()
		{
			if( !this.inited )
			{
				this.inited = true;
				if( document.all )
				{
					$( document.body ).mousedown( function( event ) {
						this.mouseDown = true;
					});
					$( "*" ).mouseup( function() {
						this.mouseDown = false;
					});
					$( document.body ).mousemove( function( event ) {
						if( !event)
						{
							event = window.event;
						}
						if( 0 == event.button )
						{
							this.mouseDown = false;
						}
					});
				}
			}
		};
		publik = statik.prototype;
		// Reference to the statik field for statik access
		publik.statik = statik;
		/**
		 * Updates the style field
		 */
		publik.onInterval = function()
		{
			if( !this.statik.mouseDown )
			{
				var time = ( new Date() ).getTime();
				this.replacer.setColor( classPath.RainbowColor.create( (time%this.properties.cycle)/this.properties.cycle, this.properties.saturation, this.properties.brightness)  );
			}
		};
		
		
		/**
		 * ColorReplacer
		 * This color replacer class adds a node to the head tag and fills it with a css.
		 * With .setColor you can change the $color text used in the style
		 *
		 * @param rules [Object] Key - value pairs containing selectors as keys and css text as values in which $color is replaced
		 */
		statik = classPath.ColorReplacer = function( rules )
		{
			this.node = document.createElement("style");
			$("head").append( this.node );
			
			this.css = "";
			this.rules = rules;
			
			for( var i in rules )
			{
				var texts = rules[i];
				var text = "";
				for( var j = 0; j<texts.length; j++ )
				{
					text += texts[j]+":$color;";
				}
				this.css += i+"{"+text+"}\n";
			}
		};
		publik = statik.prototype;
		/**
		 * Replaces the color within the text of the css node.
		 * Within the css given in the constructor it replaces the $color node
		 *
		 * @param color [{r:Number<0-1>,g:Number<0-1>,b:Number<0-1>}] color that should be put inside
		 */
		publik.setColor = function( color )
		{
			var hex = at.leichtgewicht.color.RGB.toHex( color );
			try
			{
				if( this.node.lastChild )
				{
					this.node.removeChild( this.node.lastChild );
				}
				this.node.appendChild( document.createTextNode( this.css.split("$color").join( hex ) + "\n" ) );
			}
			catch( e )
			{
				// Internet explorer requires a lot of love ... because he won't take it to change too many objects
				for( var i in this.rules )
				{
					var texts = this.rules[i];
					for( var j=0; j<texts.length; j++)
					{
						$(i).css( texts[j], hex);
					}
				}
			}
		};
		
		
		/**
		 * RainbowColor
		 * This class is a util to create a rainbow based color from a HSB class.
		 */
		statik = classPath.RainbowColor = function(){};
		/**
		 * Algorithm that creates a rainbow field from based to the percentage of rainbow
		 * 
		 * @param percentage [Number<0-1>] Percentage of the rainbow, starting from red ending from red
		 * @param s [Number<0-1>] Saturation of the rainbow
		 * @param b [Number<0-1>] Brightness of the rainbow
		 * @return [{r:[Number<0-1>],g:[Number<0-1>],b:[Number<0-1>]}] RGB value of the color
		 */
		statik.create = function( percentage, s, b )
		{
			var degree = percentage * 1080;
			degree += 180;
			var degreeOffset = Math.floor(degree/360);
			degree = degree%360;
			var offset = -Math.cos( degree / 360 * Math.PI );
			
			return at.leichtgewicht.color.HSB.toRGB( (degreeOffset * 360 + 180*offset)/1080*360, s, b);
		};
		
		
		/**
		 * RGB Util
		 */
		statik = classPath.RGB = function(){};
		/**
		 * Transforms a color to a hex value
		 *
		 * @param color [{r:Number<0-1>,g:Number<0-1>,b:Number<0-1>}] color that should be transformed
		 * @return [String] hex value for the color
		 */
		statik.toHex = function( color )
		{
			return "#"+this.toHexComponent(color.r)+this.toHexComponent(color.g)+this.toHexComponent(color.b);
		};
		/**
		 * Internal util to transform one part of the color to a hex value
		 *
		 * @param number [Number<0-1>] value to be transformed
		 * @return [String] hex value for the color part
		 */
		statik.toHexComponent = function( number )
		{
			number *= 255;
			var digits = '0123456789ABCDEF';
			var lsd = number % 16;
			var msd = (number - lsd) / 16;
			var hexified = digits.charAt(msd) + digits.charAt(lsd);
			return hexified;
		};
		
		
		/**
		 * HSB Util
		 */
		statik = classPath.HSB = function(){};
		/**
		 * Transforms a hsb color into a rgb object
		 * 
		 * @param h [Number<0-1>] hue
		 * @param s [Number<0-1>] saturation
		 * @param b [Number<0-1>] brightness
		 * @return[{r:Number<0-1>,g:Number<0-1>,b:Number<0-1>}] rgb color object for the hsb values
		 */
		statik.toRGB = function( h, s, b )
		{
			if( b <= 0 )
			{
				return 0;
			}
			b = ( b >= 1 ) ? 1 : b;
			
			if( s == 0 )
			{
				// Safe processing time with grey, are all colors all same anyway
				return {
					r: b, g: b, b: b
				}
			}
			else
			{
				if( h < 0 )
				{
					h = 360 -(-h) % 360;
				}
				h = Math.floor( h%360 );
				s = ( s >= 1 ) ? 1 : s;
				
				// the color wheel consists of 6 sectors. Figure out which sector
				// you're in.
				var sectorPos = h / 60;
				var sectorNumber = Math.floor(sectorPos);
				// get the fractional part of the sector
				var fractionalSector = sectorPos - sectorNumber;
				

				// calculate values for the three axes of the color.
				var p = b * (1 - s);
				var q = b * (1 - (s * fractionalSector));
				var t = b * (1 - (s * (1 - fractionalSector)));
				
				// assign the fractional colors to r, g, and b based on the sector
				// the angle is in.
				return {
					r: [b,q,p,p,t,b][sectorNumber],
					g: [t,b,b,q,p,p][sectorNumber],
					b: [p,p,t,b,b,q][sectorNumber]
				}
			}
		}
	}
)( window );