/**
 * Fade background Colour of element
 *
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 */
jQuery.fn.fadeBackColor = function(settings) {

	  settings = jQuery.extend({
		 startColor: null,
		 endColor: null,
		 time: null
	  }, settings);

	var elemToFade = this[0];
	var startColor = settings.startColor; 
  var endColor = settings.endColor;
  var time = settings.time;
  var cR, cG, cB, cR_end, cG_end, cB_end, ret;
	
	function hexConvert( theColor ){
		ret = [];
		theColor.replace(/(..)/g, function(theColor){
			ret.push( parseInt( theColor, 16 ) );
		});
		return ret;
	} 
	function animColor(){

		elemToFade.style.backgroundColor = 'rgb('+cR+','+cG+','+cB+')';
		if (cR < cR_end) {
			cR+= 1;		
		}
		if (cG < cG_end) {
			cG+= 1;
		}
		if (cB < cB_end) {
			cB+= 1;
		}
		if(cR != cR_end && cG != cG_end && cB != cB_end){
		 setTimeout(animColor, time);
		}
		else{
		  return this;
		}
	}

	if(startColor.indexOf("#") === 0){
		var startColorNoHash = startColor.replace(/#/, "");
		hexConvert(startColorNoHash);
		cR = ret[0];
		cG = ret[1];
		cB = ret[2];
	}
	else{
		var startColorReplace = startColor.replace(/ /g, "");
		var startColorArray = startColorReplace.substring(startColorReplace.indexOf('(')+1,startColorReplace.lastIndexOf(')')).split(",");
		cR = Number(startColorArray[0]); 
		cG = Number(startColorArray[1]); 
		cB = Number(startColorArray[2]);			
	}
	if(endColor.indexOf("#") > -1){
		var endColorNoHash = endColor.replace(/#/, "");
		hexConvert(endColorNoHash);
		cR_end = ret[0];
		cG_end = ret[1];
		cB_end = ret[2];		
	}
	else{
		var endColorReplace = endColor.replace(/ /g, "");
		var endColorArray = endColorReplace.substring(endColorReplace.indexOf('(')+1,endColorReplace.lastIndexOf(')')).split(",");
		cR_end = Number(endColorArray[0]); 
		cG_end = Number(endColorArray[1]); 
		cB_end = Number(endColorArray[2]);	
	}
	animColor();

};