// COLOUR DECODING
// Set of color decoding functions (downloaded)

// This function converts CSS rgb(x, x, x) to hexadecimal
function rgb2Hex(rgbColour){
	try{
		// Get array of RGB values
		var rgbArray = rgb2Array(rgbColour);

		// Get RGB values
		var red   = parseInt(rgbArray[0]);
		var green = parseInt(rgbArray[1]);
		var blue  = parseInt(rgbArray[2]);

		// Build hex colour code
		var hexColour = "#" + IntToHex(red) + IntToHex(green) + IntToHex(blue);
	}
	catch(e){
		alert("There was an error converting the RGB value to Hexadecimal in function rgb2Hex");
	}

	return hexColour;
}

// Returns an array of rbg values
function rgb2Array(rgbColour){
	// Remove rgb()
	var rgbValues = rgbColour.substring(4, rgbColour.indexOf(")"));

	// Split RGB into array
	var rgbArray = rgbValues.split(", ");

	return rgbArray;
}

function format_colour(colour){
	var returnColour = '#ffffff';

	// Make sure colour is set and not transparent
	if(colour != "" && colour != "transparent"){
		// RGB Value?
		if(colour.substr(0, 3) == "rgb"){
			// Get HEX aquiv.
			returnColour = rgb2Hex(colour);
		}else if(colour.length == 4){
			// 3 chr colour code add remainder
			returnColour = "#" + colour.substring(1, 2) + colour.substring(1, 2) + colour.substring(2, 3) + colour.substring(2, 3) + colour.substring(3, 4) + colour.substring(3, 4);
		}else{
			// Normal valid hex colour
			returnColour = colour;
		}
	}

	return returnColour;
}

function IntToHex(strNum){
	base = strNum / 16;
	rem = strNum % 16;
	base = base - (rem / 16);
	baseS = MakeHex(base);
	remS = MakeHex(rem);

	return baseS + '' + remS;
}

function MakeHex(x)	{
	if((x >= 0) && (x <= 9)){
		return x;
	}else{
		switch(x){
			case 10: return "A";
			case 11: return "B";
			case 12: return "C";
			case 13: return "D";
			case 14: return "E";
			case 15: return "F";
		}
	}
}
