// main function to process the fade request //
function colourFade(id,element,start,end,steps,speed,hide) {
  var startrgb,endrgb,er,eg,eb,step,rint,gint,bint,step;
  var target = document.getElementById(id);
  steps = steps || 20;
  speed = speed || 20;
  clearInterval(target.timer);
  endrgb = colourConv(end);
  er = endrgb[0];
  eg = endrgb[1];
  eb = endrgb[2];
  if(!target.r) {
    startrgb = colourConv(start);
    r = startrgb[0];
    g = startrgb[1];
    b = startrgb[2];
    target.r = r;
    target.g = g;
    target.b = b;
  }
  rint = Math.round(Math.abs(target.r-er)/steps);
  gint = Math.round(Math.abs(target.g-eg)/steps);
  bint = Math.round(Math.abs(target.b-eb)/steps);
  if(rint == 0) { rint = 1 }
  if(gint == 0) { gint = 1 }
  if(bint == 0) { bint = 1 }
  target.step = 1;
  target.timer = setInterval( function() { animateColor(id,element,steps,er,eg,eb,rint,gint,bint,hide,start,end) }, speed);
}

// incrementally close the gap between the two colours //
function animateColor(id,element,steps,er,eg,eb,rint,gint,bint,hide,startcolour,endcolour) {
  var target = document.getElementById(id);
  var colour;
  if(target.step <= steps) {
    var r = target.r;
    var g = target.g;
    var b = target.b;
    if(r >= er) {
      r = r - rint;
    } else {
      r = parseInt(r) + parseInt(rint);
    }
    if(g >= eg) {
      g = g - gint;
    } else {
      g = parseInt(g) + parseInt(gint);
    }
    if(b >= eb) {
      b = b - bint;
    } else {
      b = parseInt(b) + parseInt(bint);
    }
    colour = 'rgb(' + r + ',' + g + ',' + b + ')';
    if(element == 'background') {
      target.style.backgroundColor = colour;
    } else if(element == 'border') {
      target.style.borderColor = colour;
    } else {
      target.style.color = colour;
    }
    target.r = r;
    target.g = g;
    target.b = b;
    target.step = target.step + 1;
  } else {
	target.step=0;
	delete target.r;
    clearInterval(target.timer);
    colour = 'rgb(' + er + ',' + eg + ',' + eb + ')';
    if(element == 'background') {
      target.style.backgroundColor = colour;
    } else if(element == 'border') {
      target.style.borderColor = colour;
    } else {
      target.style.color = colour;
    }
	        if(hide==1){
                target.style.display='none';
        }
        if(hide==2){
                target.style.backgroundColor='transparent';
                target.style.backColor='transparent';
        }
        if(hide==3){
                window.setTimeout(function(){colourFade(id,element,endcolour,startcolour,steps,10,2)},100);
        }
  }
}

// convert the colour to rgb from hex //
function colourConv(colour) {
  var rgb = [parseInt(colour.substring(0,2),16), 
    parseInt(colour.substring(2,4),16), 
    parseInt(colour.substring(4,6),16)];
  return rgb;
}
