/*Created by Mike Murkovic*/
(function($) {
    $.fn.jColourStrip = function(options) {
        options = $.extend({ zeroDisplay: 'inline-block', width: '50px', height: '10px', 
		lowColour: "#ff0000", midColour: null, highColour: "#00C800", 
		border: 'solid 1px black' }, options); 
        return this.each(function(){
            var percent = $(this).attr('title');
            if (percent == 0) {
                $(this).css('display', options.zeroDisplay);
            } else {
                $(this).css('display', 'inline-block');
				var lowCol = convertHexToRGB(options.lowColour);
				var highCol = convertHexToRGB(options.highColour);
				if (options.midColour != null) {
					var midCol = convertHexToRGB(options.midColour);
					if (percent <= 0.5) {
                        var red = Math.round(lowCol["r"]*(0.5-percent)*2+midCol["r"]*percent*2);
                        var grn = Math.round(lowCol["g"]*(0.5-percent)*2+midCol["g"]*percent*2);
                        var blu = Math.round(lowCol["b"]*(0.5-percent)*2+midCol["b"]*percent*2);
                    } else {
                        var red = Math.round(midCol["r"]*(1-percent)*2+highCol["r"]*(percent-0.5)*2);
                        var grn = Math.round(midCol["g"]*(1-percent)*2+highCol["g"]*(percent-0.5)*2);
                        var blu = Math.round(midCol["b"]*(1-percent)*2+highCol["b"]*(percent-0.5)*2);
                    }
                } else {
                    var red = Math.round(lowCol["r"]*(1-percent) + highCol["r"]*percent);
                    var grn = Math.round(lowCol["g"]*(1-percent) + highCol["g"]*percent);
                    var blu = Math.round(lowCol["b"]*(1-percent) + highCol["b"]*percent);
                }
            }
			$(this).append('<div></div>');
			$(this).css('width',options.width);
			$(this).css('height',options.height);
			$(this).css('border', 'solid 1px black');
			$('div',this).css('width',percent*100+'%');
			$('div',this).css('height',options.height);
			$('div',this).css('background-color','rgb('+red+','+grn+','+blu+')');
        });
    }
	
	function convertHexToRGB(hex) {
		hex = hex.replace(/#/, '');	//remove preceding # if it's present
		var r = parseInt(hex.substring(0, 2), 16);
		var g = parseInt(hex.substring(2,4), 16);
		var b = parseInt(hex.substring(4,6), 16);
		return {"r": r, "g": g, "b": b};
	}
})(jQuery);
