/*
 * The following script is two plugins for the jQuery library.
 *
 * The first is colourfade written by myself. This adds 
 * colour fading capabilities to jQuery without layering 
 * divs and fading the alpha. 
 * (Probably already exisit out there somewhere but hey)
 *
 * The second is the innerfade plugin, written by Torsten Baldes 
 * that I have modified to include gallery navigation. This allows
 * users to select the specific image to show rather than having a 
 * random / sequenced cycle.
 *
 */


// jquery.colourfade.js

// Datum: 30-01-2009
// Author: Chris James
// Mail: drummerboof@gmail.com
(function($) {
	// Main namespace usage $('#mydiv').colourFade();
	$.fn.colourFade = function (options) {
		// Get args
		if (typeof options == 'string') { $.fn.colourFade.defaults.to = options; }
		var opts = $.extend({}, $.fn.colourFade.defaults, options);
		var n = Math.ceil(opts.speed / opts.interval);
		var t = 0;
				
		// Iterate and do it
		return this.each(function() {
			// Convenience
			$this = $(this);
			if (compare($this.css(opts.style), opts.to)) { return; }
			// Original colour variable
			var orig = getRGB($this.css(opts.style));
			// Do something
			$this.stop();
			fade($this);
		});
		
		function fade(e) {
			// ir = (speed - t) / i = iterations remaining
			// nc[x] = pc[x] - tc[x] / ir
			var pc = getRGB(e.css(opts.style));
			var tc = getRGB(opts.to);
			var nc = new Array();
			for(var x = 0; x < pc.length; x++) {
				nc.push(Math.ceil(pc[x] + (tc[x] - pc[x]) / ((opts.speed - t) / opts.interval)));
			}
			if (!hasNaN(nc)) {
				e.css(opts.style,makeHex(nc));
			}
			if (t < opts.speed) {
				setTimeout(function() {
					fade(e);				
				}, opts.interval);
				t+=opts.interval;
			}
		};

	};
	
	// Plugin defaults
	$.fn.colourFade.defaults = {
		speed: 		1000,
		to: 		'#FFFFFF',
		interval: 	25,
		style: 		'background-color'
	};
	
	// Private method to get colour array from css
	function getRGB(c) {
		//var c = e.css('background-color');
		var rgb = new Array();
		if (c.substr(0,1) == "#") { // #FFF / #FFFFFF
			c = c.substr(1, c.length-1);
			if (c.length == 3) {
				for (x = 0; x < c.length; x++) { var z=c.substr(x, 1); rgb.push(h2d(z+z)); }
			} else {
				for (x = 0; x < c.length; x += 2) { rgb.push(h2d(c.substr(x, 2))); }	
			}
		} else { // rgb(255,255,255)
			var bits = c.replace('rgb(', '').split(',');
			for (x = 0; x < bits.length; x++) { rgb.push(parseInt(bits[x])); }
		}
		return rgb;
	};
	
	// Private method for hex colour creation
	function makeHex(rgb) {
		var hexOut = "#";
		for (x = 0; x < rgb.length; x++) {
			hexOut += d2h(rgb[x]);
		}
		return hexOut;
	};
	
	function compare (co,ct) {
		co = getRGB(co); ct = getRGB(ct);
		for (var x = 0; x < co.length; x++) { if (co[x] != ct[x]) return false;	}
		return true;
	};
	
	function hasNaN (ca) {
		for (var x = 0; x < ca.length; x++) { if (isNaN(ca[x])) { return true; } } return false;
	};
	function d2h(d) { 
		var h = d.toString(16); 
		return (h.length < 2) ? '0'+h : h;
	};
	
	function h2d(h) { 
		return parseInt(h, 16); 
	}; 
	
	function debug(msg) {
		$('#debug').append(msg + '<br />');	
	}

})(jQuery);



// jquery.innerfade.js

// Datum: 2008-02-14
// Firma: Medienfreunde Hofmann & Baldes GbR
// Author: Torsten Baldes
// Mail: t.baldes@medienfreunde.com
// Web: http://medienfreunde.com

// based on the work of Matt Oakes http://portfolio.gizone.co.uk/applications/slideshow/
// and Ralf S. Engelschall http://trainofthoughts.org/


// ========================================
// Modified to add navigation functionality
//   Used as gallery with controlling element
//   Uses colourfade for gallery controller 
//   hover / selections.
//   
//   I have updated the name to colourgallery
//   This is simply a modified version of innerfade
//   
//   Mdified by: Chris James
//   Date:       30-01-2009
//
// ========================================
(function($) {

    $.fn.colourgallery = function(options) {
        return this.each(function() {   
            $.colourgallery(this, options);
        });
    };
	var goto_last = 0;
    $.colourgallery = function(container, options) {
        var settings = {
        	'animationtype':    'fade',
            'speed':            'normal',
            'type':             'sequence',
            'timeout':          2000,
            'containerheight':  'auto',
            'runningclass':     'colourgallery',
			'controller':		'#controller', 
            'children':         null,
            'fadeclick': 		false,
            'fadehover': 		false,
            'colouron': 		'#FF9900',
            'colouroff': 		'#CECECE',
            'fadespeed': 		200
        };
		
        if (options)
            $.extend(settings, options);
        if (settings.children === null)
            var elements = $(container).children();
        else
            var elements = $(container).children(settings.children);
        if (elements.length > 1) {
			// ================================================
			// Click event handlers for the controller
			// ================================================
			var controller_kids = $(settings.controller).children();
			var current = null;
			controller_kids.each(function(i) {
				if (settings.fadehover) {
					$(this).hover(function() {
						$(this).colourFade({speed: settings.fadespeed, to: settings.colouron});	
					}, function() {
						if (i != goto_last) {
							$(this).colourFade({speed: settings.fadespeed, to: settings.colouroff});
						}
					});
				}
				$(this).click(function() {
					$.colourgallery.goto(elements, controller_kids, settings, i, goto_last);
					return false;
				});
			});
			// ================================================
			// END Click event handlers for the controller
			// ================================================
			$(container).css('position', 'relative').css('height', settings.containerheight).addClass(settings.runningclass);
            for (var i = 0; i < elements.length; i++) {
                $(elements[i]).css('z-index', String(elements.length-i)).css('position', 'absolute').hide();
            };
            if (settings.type == "sequence") {
                setTimeout(function() {
                    $.colourgallery.next(elements, settings, 1, 0);
                }, settings.timeout);
                $(elements[0]).show();
            } else if (settings.type == "random") {
            	var last = Math.floor ( Math.random () * ( elements.length ) );
                setTimeout(function() {
                	do { 
						current = Math.floor ( Math.random ( ) * ( elements.length ) );
					} while (last == current );             
					$.colourgallery.next(elements, settings, current, last);
                }, settings.timeout);
                $(elements[last]).show();
			} else if ( settings.type == 'random_start' ) {
					settings.type = 'sequence';
					var current = Math.floor ( Math.random () * ( elements.length ) );
					setTimeout(function(){d
						$.colourgallery.next(elements, settings, (current + 1) %  elements.length, current);
					}, settings.timeout);
					$(elements[current]).show();
			// ================================================
			// New type setting - controlled - uses a navigator
			// ================================================
			} else if (settings.type == "controlled") {
				$.colourgallery.goto(elements, controller_kids, settings, 0, null);
			} else {
				alert('colourgallery-Type must either be \'sequence\', \'random\' or \'random_start\'');
			}
		}
    };
	// ============================================
	// New function goto - jump to a specific image
	// ============================================
	$.colourgallery.goto = function(elements, controller_kids, settings, current, last) {
		if (current == last) return;
		if (settings.fadeclick) {
			if (last != null) {
				$(controller_kids[last]).colourFade({speed: settings.fadespeed, to: settings.colouroff});
			}
			$(controller_kids[current]).colourFade({speed: settings.fadespeed, to: settings.colouron});
		}
        if (settings.animationtype == 'slide') {
            $(elements[last]).slideUp(settings.speed);
            $(elements[current]).slideDown(settings.speed);
        } else if (settings.animationtype == 'fade') {
			
            $(elements[last]).fadeOut(settings.speed);
            $(elements[current]).fadeIn(settings.speed, function() {
				removeFilter($(this)[0]);
			});
        } else {
            alert('colourgallery-animationtype must either be \'slide\' or \'fade\'');
		}
		goto_last = current;
	};
	// ========================================
	//END goto
	// ========================================

    $.colourgallery.next = function(elements, settings, current, last) {
        if (settings.animationtype == 'slide') {
            $(elements[last]).slideUp(settings.speed);
            $(elements[current]).slideDown(settings.speed);
        } else if (settings.animationtype == 'fade') {
            $(elements[last]).fadeOut(settings.speed);
            $(elements[current]).fadeIn(settings.speed, function() {
				removeFilter($(this)[0]);
			});
        } else {
            alert('colourgallery-animationtype must either be \'slide\' or \'fade\'');
		}
        if (settings.type == "sequence") {
            if ((current + 1) < elements.length) {
                current = current + 1;
                last = current - 1;
            } else {
                current = 0;
                last = elements.length - 1;
            }
        } else if (settings.type == "random") {
            last = current;
            while (current == last)
                current = Math.floor(Math.random() * elements.length);
		} else if (settings.type == "controlled") {
			
        } else
            alert('colourgallery-Type must either be \'sequence\', \'random\' or \'random_start\'');
        setTimeout((function() {
            $.colourgallery.next(elements, settings, current, last);
        }), settings.timeout);
    };

})(jQuery);

// **** remove Opacity-Filter in ie ****
function removeFilter(element) {
	if(element.style.removeAttribute){
		element.style.removeAttribute('filter');
	}
}
