var color1 = '#FFFFFF';
var color2 = '#FFDE00';

function fade(id, c1, c2) {
	var e = document.getElementById(id);
	if (!e) return;
	
	var color = style2hex(e.style.backgroundColor);
	if (color == '#000000') color = c1;	
	
	fadeElement(id, color, c2);
}

function fadeElement(id, color_s, color_e) {
	var e = document.getElementById(id);
	if (!e) return;
	if (e.bgFade) window.clearInterval(e.bgFade);
	
	e.bgFade = window.setInterval(
		function() {
			var start= hex2num(color_s);
			var stop = hex2num(color_e);
		
			for(var i = 0; i < 3; i++) {
				start[i] = Number(start[i]);
				stop[i] = Number(stop[i]);
			}
		
			for(var i = 0; i < 3; i++) {
				if (start[i] < stop[i]) {
					start[i] += 10;
					if(start[i] > stop[i]) start[i] = stop[i];
				} else if(start[i] > stop[i]) {
					start[i] -= 10;
					if(start[i] < stop[i]) start[i] = stop[i];
				}
			}
			
			e.style.backgroundColor = "rgb("+start[0]+","+start[1]+","+start[2]+")";
			if ((start[0] == stop[0]) && (start[1] == stop[1]) && (start[2] == stop[2])) {
				window.clearInterval(e.bgFade);
			}
			color_s = num2hex(start);
		}, 30);
}

function hex2num(hex) {
	if(hex.charAt(0) == "#") { 
		hex = hex.slice(1);
	}
	hex = hex.toUpperCase();
	var hex_alphabets = "0123456789ABCDEF";
	var value = new Array(3);
	var k = 0;
	var int1,int2;
	for(var i=0; i<6; i+=2) {
		int1 = hex_alphabets.indexOf(hex.charAt(i));
		int2 = hex_alphabets.indexOf(hex.charAt(i+1));
		value[k] = (int1 * 16) + int2;
		k++;
	}
	return(value);
}

function num2hex(triplet) {
	var hex_alphabets = "0123456789ABCDEF";
	var hex = "#";
	var int1,int2;
	for(var i=0; i<3; i++) {
		int1 = triplet[i] / 16;
		int2 = triplet[i] % 16;
		hex += hex_alphabets.charAt(int1) + hex_alphabets.charAt(int2);
	}
	return(hex);
}

function style2hex(style) {
	if (style.charAt(0) == '#') return style.toUpperCase();
	
	var i1 = style.indexOf('(');
	var i2 = style.indexOf(')');
	var txt = style.substr(i1+1, i2-i1-1);
	var tmp = txt.split(',');
	return num2hex(tmp);
}

var maxFade = 100;
var minFade = 20;
	
function fadeImage(id, fadeIn) {
	
	var img = document.getElementById(id);	
	if (img.fade) window.clearInterval(img.fade);

	if(fadeIn) img.cur = minFade; else img.cur = maxFade;
	
	img.fade = window.setInterval(
		function() {

			if (fadeIn)	img.cur += 10; else	img.cur -= 10;
			if ((img.cur == minFade) || (img.cur == maxFade)) {
				window.clearInterval(img.fade);
			} else {
				img.style.opacity = '0.'+img.cur;
				img.style.filter = 'alpha(opacity='+img.cur+')';	
			}
		}, 20);
}

