﻿colorFade = {
    hex2num : function(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);
    },
    num2hex : function(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);
    },
    fadeColor : function(id,start_hex,stop_hex,difference,delay,color_background) {
        if(!difference) 
            difference = 20;
        if(!delay) 
            delay = 100;
        if(!start_hex) 
            start_hex = "#FFFFFF";
        if(!stop_hex) 
            stop_hex = "#000000";
        if(!color_background) 
            color_background = "c";

        var ele = document.getElementById(id);
        if(!ele) 
            return;
        var start= this.hex2num(start_hex);
        var stop = this.hex2num(stop_hex);

        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] += difference;
                if(start[i] > stop[i]) 
                    start[i] = stop[i];
            }
            else if(start[i] > stop[i]) {
                start[i] -= difference;
                    if(start[i] < stop[i]) 
                        start[i] = stop[i];
            }
        }

        var color = "rgb("+start[0]+","+start[1]+","+start[2]+")";
        if(color_background == "b") {
            ele.style.backgroundColor = color;
        } else {
            ele.style.color = color;
        }

        if((start[0] == stop[0]) && (start[1] == stop[1]) && (start[2] == stop[2]))
            return;

        start_hex = this.num2hex(start);

        window.setTimeout("colorFade.fadeColor('"+id+"','"+start_hex+"','"+stop_hex+"',"+difference+","+delay+",'"+color_background+"')",delay);
    }
}